babylon.max.js 5.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917
  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], { oneTimeOnly: true });
  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) || Object.assign || function(t) {
  11186. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11187. s = arguments[i];
  11188. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11189. t[p] = s[p];
  11190. }
  11191. return t;
  11192. };
  11193. var BABYLON;
  11194. (function (BABYLON) {
  11195. /**
  11196. * Keeps track of all the buffer info used in engine.
  11197. */
  11198. var BufferPointer = /** @class */ (function () {
  11199. function BufferPointer() {
  11200. }
  11201. return BufferPointer;
  11202. }());
  11203. /**
  11204. * Interface for attribute information associated with buffer instanciation
  11205. */
  11206. var InstancingAttributeInfo = /** @class */ (function () {
  11207. function InstancingAttributeInfo() {
  11208. }
  11209. return InstancingAttributeInfo;
  11210. }());
  11211. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11212. /**
  11213. * Define options used to create a render target texture
  11214. */
  11215. var RenderTargetCreationOptions = /** @class */ (function () {
  11216. function RenderTargetCreationOptions() {
  11217. }
  11218. return RenderTargetCreationOptions;
  11219. }());
  11220. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11221. /**
  11222. * Define options used to create a depth texture
  11223. */
  11224. var DepthTextureCreationOptions = /** @class */ (function () {
  11225. function DepthTextureCreationOptions() {
  11226. }
  11227. return DepthTextureCreationOptions;
  11228. }());
  11229. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11230. /**
  11231. * Class used to describe the capabilities of the engine relatively to the current browser
  11232. */
  11233. var EngineCapabilities = /** @class */ (function () {
  11234. function EngineCapabilities() {
  11235. }
  11236. return EngineCapabilities;
  11237. }());
  11238. BABYLON.EngineCapabilities = EngineCapabilities;
  11239. /**
  11240. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11241. */
  11242. var Engine = /** @class */ (function () {
  11243. /**
  11244. * Creates a new engine
  11245. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11246. * @param antialias defines enable antialiasing (default: false)
  11247. * @param options defines further options to be sent to the getContext() function
  11248. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11249. */
  11250. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11251. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11252. var _this = this;
  11253. // Public members
  11254. /**
  11255. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11256. */
  11257. this.forcePOTTextures = false;
  11258. /**
  11259. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11260. */
  11261. this.isFullscreen = false;
  11262. /**
  11263. * Gets a boolean indicating if the pointer is currently locked
  11264. */
  11265. this.isPointerLock = false;
  11266. /**
  11267. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11268. */
  11269. this.cullBackFaces = true;
  11270. /**
  11271. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11272. */
  11273. this.renderEvenInBackground = true;
  11274. /**
  11275. * Gets or sets a boolean indicating that cache can be kept between frames
  11276. */
  11277. this.preventCacheWipeBetweenFrames = false;
  11278. /**
  11279. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11280. **/
  11281. this.enableOfflineSupport = false;
  11282. /**
  11283. * 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)
  11284. **/
  11285. this.disableManifestCheck = false;
  11286. /**
  11287. * Gets the list of created scenes
  11288. */
  11289. this.scenes = new Array();
  11290. /**
  11291. * Gets the list of created postprocesses
  11292. */
  11293. this.postProcesses = new Array();
  11294. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11295. this.validateShaderPrograms = false;
  11296. // Observables
  11297. /**
  11298. * Observable event triggered each time the rendering canvas is resized
  11299. */
  11300. this.onResizeObservable = new BABYLON.Observable();
  11301. /**
  11302. * Observable event triggered each time the canvas loses focus
  11303. */
  11304. this.onCanvasBlurObservable = new BABYLON.Observable();
  11305. /**
  11306. * Observable event triggered each time the canvas gains focus
  11307. */
  11308. this.onCanvasFocusObservable = new BABYLON.Observable();
  11309. /**
  11310. * Observable event triggered each time the canvas receives pointerout event
  11311. */
  11312. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11313. /**
  11314. * Observable event triggered before each texture is initialized
  11315. */
  11316. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11317. //WebVR
  11318. this._vrDisplay = undefined;
  11319. this._vrSupported = false;
  11320. this._vrExclusivePointerMode = false;
  11321. // Uniform buffers list
  11322. /**
  11323. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11324. */
  11325. this.disableUniformBuffers = false;
  11326. /** @hidden */
  11327. this._uniformBuffers = new Array();
  11328. // Observables
  11329. /**
  11330. * Observable raised when the engine begins a new frame
  11331. */
  11332. this.onBeginFrameObservable = new BABYLON.Observable();
  11333. /**
  11334. * Observable raised when the engine ends the current frame
  11335. */
  11336. this.onEndFrameObservable = new BABYLON.Observable();
  11337. /**
  11338. * Observable raised when the engine is about to compile a shader
  11339. */
  11340. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11341. /**
  11342. * Observable raised when the engine has jsut compiled a shader
  11343. */
  11344. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11345. this._windowIsBackground = false;
  11346. this._webGLVersion = 1.0;
  11347. /** @hidden */
  11348. this._badOS = false;
  11349. /** @hidden */
  11350. this._badDesktopOS = false;
  11351. /**
  11352. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11353. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11354. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11355. */
  11356. this.disableTextureBindingOptimization = false;
  11357. /**
  11358. * Observable signaled when VR display mode changes
  11359. */
  11360. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11361. /**
  11362. * Observable signaled when VR request present is complete
  11363. */
  11364. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11365. /**
  11366. * Observable signaled when VR request present starts
  11367. */
  11368. this.onVRRequestPresentStart = new BABYLON.Observable();
  11369. this._colorWrite = true;
  11370. /** @hidden */
  11371. this._drawCalls = new BABYLON.PerfCounter();
  11372. /** @hidden */
  11373. this._textureCollisions = new BABYLON.PerfCounter();
  11374. this._renderingQueueLaunched = false;
  11375. this._activeRenderLoops = new Array();
  11376. // Deterministic lockstepMaxSteps
  11377. this._deterministicLockstep = false;
  11378. this._lockstepMaxSteps = 4;
  11379. // Lost context
  11380. /**
  11381. * Observable signaled when a context lost event is raised
  11382. */
  11383. this.onContextLostObservable = new BABYLON.Observable();
  11384. /**
  11385. * Observable signaled when a context restored event is raised
  11386. */
  11387. this.onContextRestoredObservable = new BABYLON.Observable();
  11388. this._contextWasLost = false;
  11389. this._doNotHandleContextLost = false;
  11390. // FPS
  11391. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11392. this._fps = 60;
  11393. this._deltaTime = 0;
  11394. /**
  11395. * Turn this value on if you want to pause FPS computation when in background
  11396. */
  11397. this.disablePerformanceMonitorInBackground = false;
  11398. // States
  11399. /** @hidden */
  11400. this._depthCullingState = new BABYLON._DepthCullingState();
  11401. /** @hidden */
  11402. this._stencilState = new BABYLON._StencilState();
  11403. /** @hidden */
  11404. this._alphaState = new BABYLON._AlphaState();
  11405. /** @hidden */
  11406. this._alphaMode = Engine.ALPHA_DISABLE;
  11407. // Cache
  11408. this._internalTexturesCache = new Array();
  11409. /** @hidden */
  11410. this._activeChannel = 0;
  11411. this._currentTextureChannel = -1;
  11412. /** @hidden */
  11413. this._boundTexturesCache = {};
  11414. this._compiledEffects = {};
  11415. this._vertexAttribArraysEnabled = [];
  11416. this._uintIndicesCurrentlySet = false;
  11417. this._currentBoundBuffer = new Array();
  11418. /** @hidden */
  11419. this._currentFramebuffer = null;
  11420. this._currentBufferPointers = new Array();
  11421. this._currentInstanceLocations = new Array();
  11422. this._currentInstanceBuffers = new Array();
  11423. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11424. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11425. this._vaoRecordInProgress = false;
  11426. this._mustWipeVertexAttributes = false;
  11427. this._nextFreeTextureSlots = new Array();
  11428. this._maxSimultaneousTextures = 0;
  11429. this._activeRequests = new Array();
  11430. // Hardware supported Compressed Textures
  11431. this._texturesSupported = new Array();
  11432. /**
  11433. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11434. */
  11435. this.premultipliedAlpha = true;
  11436. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11437. this._onVRFullScreenTriggered = function () {
  11438. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11439. //get the old size before we change
  11440. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11441. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11442. //get the width and height, change the render size
  11443. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11444. _this.setHardwareScalingLevel(1);
  11445. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11446. }
  11447. else {
  11448. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11449. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11450. }
  11451. };
  11452. this._unpackFlipYCached = null;
  11453. this._boundUniforms = {};
  11454. // Register promises
  11455. BABYLON.PromisePolyfill.Apply();
  11456. var canvas = null;
  11457. Engine.Instances.push(this);
  11458. if (!canvasOrContext) {
  11459. return;
  11460. }
  11461. options = options || {};
  11462. if (canvasOrContext.getContext) {
  11463. canvas = canvasOrContext;
  11464. this._renderingCanvas = canvas;
  11465. if (antialias != null) {
  11466. options.antialias = antialias;
  11467. }
  11468. if (options.deterministicLockstep === undefined) {
  11469. options.deterministicLockstep = false;
  11470. }
  11471. if (options.lockstepMaxSteps === undefined) {
  11472. options.lockstepMaxSteps = 4;
  11473. }
  11474. if (options.preserveDrawingBuffer === undefined) {
  11475. options.preserveDrawingBuffer = false;
  11476. }
  11477. if (options.audioEngine === undefined) {
  11478. options.audioEngine = true;
  11479. }
  11480. if (options.stencil === undefined) {
  11481. options.stencil = true;
  11482. }
  11483. if (options.premultipliedAlpha === false) {
  11484. this.premultipliedAlpha = false;
  11485. }
  11486. this._deterministicLockstep = options.deterministicLockstep;
  11487. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11488. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11489. // Exceptions
  11490. if (navigator && navigator.userAgent) {
  11491. var ua = navigator.userAgent;
  11492. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11493. var exception = _a[_i];
  11494. var key = exception.key;
  11495. var targets = exception.targets;
  11496. if (ua.indexOf(key) > -1) {
  11497. if (exception.capture && exception.captureConstraint) {
  11498. var capture = exception.capture;
  11499. var constraint = exception.captureConstraint;
  11500. var regex = new RegExp(capture);
  11501. var matches = regex.exec(ua);
  11502. if (matches && matches.length > 0) {
  11503. var capturedValue = parseInt(matches[matches.length - 1]);
  11504. if (capturedValue >= constraint) {
  11505. continue;
  11506. }
  11507. }
  11508. }
  11509. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11510. var target = targets_1[_b];
  11511. switch (target) {
  11512. case "uniformBuffer":
  11513. this.disableUniformBuffers = true;
  11514. break;
  11515. case "textureBindingOptimization":
  11516. this.disableTextureBindingOptimization = true;
  11517. break;
  11518. }
  11519. }
  11520. }
  11521. }
  11522. }
  11523. // GL
  11524. if (!options.disableWebGL2Support) {
  11525. try {
  11526. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11527. if (this._gl) {
  11528. this._webGLVersion = 2.0;
  11529. }
  11530. }
  11531. catch (e) {
  11532. // Do nothing
  11533. }
  11534. }
  11535. if (!this._gl) {
  11536. if (!canvas) {
  11537. throw new Error("The provided canvas is null or undefined.");
  11538. }
  11539. try {
  11540. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11541. }
  11542. catch (e) {
  11543. throw new Error("WebGL not supported");
  11544. }
  11545. }
  11546. if (!this._gl) {
  11547. throw new Error("WebGL not supported");
  11548. }
  11549. this._onCanvasFocus = function () {
  11550. _this.onCanvasFocusObservable.notifyObservers(_this);
  11551. };
  11552. this._onCanvasBlur = function () {
  11553. _this.onCanvasBlurObservable.notifyObservers(_this);
  11554. };
  11555. canvas.addEventListener("focus", this._onCanvasFocus);
  11556. canvas.addEventListener("blur", this._onCanvasBlur);
  11557. this._onBlur = function () {
  11558. if (_this.disablePerformanceMonitorInBackground) {
  11559. _this._performanceMonitor.disable();
  11560. }
  11561. _this._windowIsBackground = true;
  11562. };
  11563. this._onFocus = function () {
  11564. if (_this.disablePerformanceMonitorInBackground) {
  11565. _this._performanceMonitor.enable();
  11566. }
  11567. _this._windowIsBackground = false;
  11568. };
  11569. this._onCanvasPointerOut = function (ev) {
  11570. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11571. };
  11572. window.addEventListener("blur", this._onBlur);
  11573. window.addEventListener("focus", this._onFocus);
  11574. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11575. // Context lost
  11576. if (!this._doNotHandleContextLost) {
  11577. this._onContextLost = function (evt) {
  11578. evt.preventDefault();
  11579. _this._contextWasLost = true;
  11580. BABYLON.Tools.Warn("WebGL context lost.");
  11581. _this.onContextLostObservable.notifyObservers(_this);
  11582. };
  11583. this._onContextRestored = function (evt) {
  11584. // Adding a timeout to avoid race condition at browser level
  11585. setTimeout(function () {
  11586. // Rebuild gl context
  11587. _this._initGLContext();
  11588. // Rebuild effects
  11589. _this._rebuildEffects();
  11590. // Rebuild textures
  11591. _this._rebuildInternalTextures();
  11592. // Rebuild buffers
  11593. _this._rebuildBuffers();
  11594. // Cache
  11595. _this.wipeCaches(true);
  11596. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11597. _this.onContextRestoredObservable.notifyObservers(_this);
  11598. _this._contextWasLost = false;
  11599. }, 0);
  11600. };
  11601. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11602. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11603. }
  11604. }
  11605. else {
  11606. this._gl = canvasOrContext;
  11607. this._renderingCanvas = this._gl.canvas;
  11608. if (this._gl.renderbufferStorageMultisample) {
  11609. this._webGLVersion = 2.0;
  11610. }
  11611. options.stencil = this._gl.getContextAttributes().stencil;
  11612. }
  11613. // Viewport
  11614. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11615. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11616. this.resize();
  11617. this._isStencilEnable = options.stencil ? true : false;
  11618. this._initGLContext();
  11619. if (canvas) {
  11620. // Fullscreen
  11621. this._onFullscreenChange = function () {
  11622. if (document.fullscreen !== undefined) {
  11623. _this.isFullscreen = document.fullscreen;
  11624. }
  11625. else if (document.mozFullScreen !== undefined) {
  11626. _this.isFullscreen = document.mozFullScreen;
  11627. }
  11628. else if (document.webkitIsFullScreen !== undefined) {
  11629. _this.isFullscreen = document.webkitIsFullScreen;
  11630. }
  11631. else if (document.msIsFullScreen !== undefined) {
  11632. _this.isFullscreen = document.msIsFullScreen;
  11633. }
  11634. // Pointer lock
  11635. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11636. canvas.requestPointerLock = canvas.requestPointerLock ||
  11637. canvas.msRequestPointerLock ||
  11638. canvas.mozRequestPointerLock ||
  11639. canvas.webkitRequestPointerLock;
  11640. if (canvas.requestPointerLock) {
  11641. canvas.requestPointerLock();
  11642. }
  11643. }
  11644. };
  11645. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11646. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11647. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11648. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11649. // Pointer lock
  11650. this._onPointerLockChange = function () {
  11651. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11652. document.webkitPointerLockElement === canvas ||
  11653. document.msPointerLockElement === canvas ||
  11654. document.pointerLockElement === canvas);
  11655. };
  11656. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11657. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11658. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11659. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11660. this._onVRDisplayPointerRestricted = function () {
  11661. if (canvas) {
  11662. canvas.requestPointerLock();
  11663. }
  11664. };
  11665. this._onVRDisplayPointerUnrestricted = function () {
  11666. document.exitPointerLock();
  11667. };
  11668. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11669. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11670. }
  11671. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11672. Engine.audioEngine = new BABYLON.AudioEngine();
  11673. }
  11674. // Prepare buffer pointers
  11675. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11676. this._currentBufferPointers[i] = new BufferPointer();
  11677. }
  11678. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11679. // Load WebVR Devices
  11680. if (options.autoEnableWebVR) {
  11681. this.initWebVR();
  11682. }
  11683. // Detect if we are running on a faulty buggy OS.
  11684. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11685. // Detect if we are running on a faulty buggy desktop OS.
  11686. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11687. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11688. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11689. }
  11690. Object.defineProperty(Engine, "LastCreatedEngine", {
  11691. /**
  11692. * Gets the latest created engine
  11693. */
  11694. get: function () {
  11695. if (Engine.Instances.length === 0) {
  11696. return null;
  11697. }
  11698. return Engine.Instances[Engine.Instances.length - 1];
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. Object.defineProperty(Engine, "LastCreatedScene", {
  11704. /**
  11705. * Gets the latest created scene
  11706. */
  11707. get: function () {
  11708. var lastCreatedEngine = Engine.LastCreatedEngine;
  11709. if (!lastCreatedEngine) {
  11710. return null;
  11711. }
  11712. if (lastCreatedEngine.scenes.length === 0) {
  11713. return null;
  11714. }
  11715. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. /**
  11721. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11722. * @param flag defines which part of the materials must be marked as dirty
  11723. * @param predicate defines a predicate used to filter which materials should be affected
  11724. */
  11725. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11726. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11727. var engine = Engine.Instances[engineIndex];
  11728. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11729. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11730. }
  11731. }
  11732. };
  11733. Object.defineProperty(Engine, "Version", {
  11734. /**
  11735. * Returns the current version of the framework
  11736. */
  11737. get: function () {
  11738. return "3.3.0-alpha.13";
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11744. /**
  11745. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11746. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11747. */
  11748. get: function () {
  11749. return this._vrExclusivePointerMode;
  11750. },
  11751. enumerable: true,
  11752. configurable: true
  11753. });
  11754. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11755. /**
  11756. * Gets a boolean indicating that the engine supports uniform buffers
  11757. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11758. */
  11759. get: function () {
  11760. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11761. },
  11762. enumerable: true,
  11763. configurable: true
  11764. });
  11765. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11766. /**
  11767. * Gets a boolean indicating that only power of 2 textures are supported
  11768. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11769. */
  11770. get: function () {
  11771. return this._webGLVersion < 2 || this.forcePOTTextures;
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11777. /**
  11778. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11779. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11780. */
  11781. get: function () {
  11782. return this._doNotHandleContextLost;
  11783. },
  11784. set: function (value) {
  11785. this._doNotHandleContextLost = value;
  11786. },
  11787. enumerable: true,
  11788. configurable: true
  11789. });
  11790. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11791. /**
  11792. * Gets the performance monitor attached to this engine
  11793. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11794. */
  11795. get: function () {
  11796. return this._performanceMonitor;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11802. /**
  11803. * Gets the list of texture formats supported
  11804. */
  11805. get: function () {
  11806. return this._texturesSupported;
  11807. },
  11808. enumerable: true,
  11809. configurable: true
  11810. });
  11811. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11812. /**
  11813. * Gets the list of texture formats in use
  11814. */
  11815. get: function () {
  11816. return this._textureFormatInUse;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine.prototype, "currentViewport", {
  11822. /**
  11823. * Gets the current viewport
  11824. */
  11825. get: function () {
  11826. return this._cachedViewport;
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11832. /**
  11833. * Gets the default empty texture
  11834. */
  11835. get: function () {
  11836. if (!this._emptyTexture) {
  11837. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11838. }
  11839. return this._emptyTexture;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11845. /**
  11846. * Gets the default empty 3D texture
  11847. */
  11848. get: function () {
  11849. if (!this._emptyTexture3D) {
  11850. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11851. }
  11852. return this._emptyTexture3D;
  11853. },
  11854. enumerable: true,
  11855. configurable: true
  11856. });
  11857. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11858. /**
  11859. * Gets the default empty cube texture
  11860. */
  11861. get: function () {
  11862. if (!this._emptyCubeTexture) {
  11863. var faceData = new Uint8Array(4);
  11864. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11865. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11866. }
  11867. return this._emptyCubeTexture;
  11868. },
  11869. enumerable: true,
  11870. configurable: true
  11871. });
  11872. Engine.prototype._rebuildInternalTextures = function () {
  11873. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11874. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11875. var internalTexture = currentState_1[_i];
  11876. internalTexture._rebuild();
  11877. }
  11878. };
  11879. Engine.prototype._rebuildEffects = function () {
  11880. for (var key in this._compiledEffects) {
  11881. var effect = this._compiledEffects[key];
  11882. effect._prepareEffect();
  11883. }
  11884. BABYLON.Effect.ResetCache();
  11885. };
  11886. Engine.prototype._rebuildBuffers = function () {
  11887. // Index / Vertex
  11888. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11889. var scene = _a[_i];
  11890. scene.resetCachedMaterial();
  11891. scene._rebuildGeometries();
  11892. scene._rebuildTextures();
  11893. }
  11894. // Uniforms
  11895. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11896. var uniformBuffer = _c[_b];
  11897. uniformBuffer._rebuild();
  11898. }
  11899. };
  11900. Engine.prototype._initGLContext = function () {
  11901. // Caps
  11902. this._caps = new EngineCapabilities();
  11903. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11904. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11905. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11906. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11907. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11908. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11909. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11910. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11911. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11912. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11913. // Infos
  11914. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11915. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11916. if (rendererInfo != null) {
  11917. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11918. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11919. }
  11920. if (!this._glVendor) {
  11921. this._glVendor = "Unknown vendor";
  11922. }
  11923. if (!this._glRenderer) {
  11924. this._glRenderer = "Unknown renderer";
  11925. }
  11926. // Constants
  11927. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11928. if (this._gl.RGBA16F !== 0x881A) {
  11929. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11930. }
  11931. if (this._gl.RGBA32F !== 0x8814) {
  11932. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11933. }
  11934. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11935. this._gl.DEPTH24_STENCIL8 = 35056;
  11936. }
  11937. // Extensions
  11938. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11939. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11940. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11941. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11942. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11943. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11944. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11945. 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');
  11946. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11947. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11948. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11949. this._caps.highPrecisionShaderSupported = true;
  11950. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11951. if (this._caps.timerQuery) {
  11952. if (this._webGLVersion === 1) {
  11953. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11954. }
  11955. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11956. }
  11957. // Checks if some of the format renders first to allow the use of webgl inspector.
  11958. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11959. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11960. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11961. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11962. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11963. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11964. if (this._webGLVersion > 1) {
  11965. this._gl.HALF_FLOAT_OES = 0x140B;
  11966. }
  11967. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11968. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11969. // Draw buffers
  11970. if (this._webGLVersion > 1) {
  11971. this._caps.drawBuffersExtension = true;
  11972. }
  11973. else {
  11974. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11975. if (drawBuffersExtension !== null) {
  11976. this._caps.drawBuffersExtension = true;
  11977. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11978. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11979. for (var i = 0; i < 16; i++) {
  11980. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11981. }
  11982. }
  11983. else {
  11984. this._caps.drawBuffersExtension = false;
  11985. }
  11986. }
  11987. // Depth Texture
  11988. if (this._webGLVersion > 1) {
  11989. this._caps.depthTextureExtension = true;
  11990. }
  11991. else {
  11992. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11993. if (depthTextureExtension != null) {
  11994. this._caps.depthTextureExtension = true;
  11995. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11996. }
  11997. }
  11998. // Vertex array object
  11999. if (this._webGLVersion > 1) {
  12000. this._caps.vertexArrayObject = true;
  12001. }
  12002. else {
  12003. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12004. if (vertexArrayObjectExtension != null) {
  12005. this._caps.vertexArrayObject = true;
  12006. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12007. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12008. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12009. }
  12010. else {
  12011. this._caps.vertexArrayObject = false;
  12012. }
  12013. }
  12014. // Instances count
  12015. if (this._webGLVersion > 1) {
  12016. this._caps.instancedArrays = true;
  12017. }
  12018. else {
  12019. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12020. if (instanceExtension != null) {
  12021. this._caps.instancedArrays = true;
  12022. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12023. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12024. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12025. }
  12026. else {
  12027. this._caps.instancedArrays = false;
  12028. }
  12029. }
  12030. // Intelligently add supported compressed formats in order to check for.
  12031. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12032. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12033. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12034. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12035. if (this._caps.astc)
  12036. this.texturesSupported.push('-astc.ktx');
  12037. if (this._caps.s3tc)
  12038. this.texturesSupported.push('-dxt.ktx');
  12039. if (this._caps.pvrtc)
  12040. this.texturesSupported.push('-pvrtc.ktx');
  12041. if (this._caps.etc2)
  12042. this.texturesSupported.push('-etc2.ktx');
  12043. if (this._caps.etc1)
  12044. this.texturesSupported.push('-etc1.ktx');
  12045. if (this._gl.getShaderPrecisionFormat) {
  12046. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12047. if (highp) {
  12048. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12049. }
  12050. }
  12051. // Depth buffer
  12052. this.setDepthBuffer(true);
  12053. this.setDepthFunctionToLessOrEqual();
  12054. this.setDepthWrite(true);
  12055. // Texture maps
  12056. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12057. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12058. this._nextFreeTextureSlots.push(slot);
  12059. }
  12060. };
  12061. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12062. /**
  12063. * Gets version of the current webGL context
  12064. */
  12065. get: function () {
  12066. return this._webGLVersion;
  12067. },
  12068. enumerable: true,
  12069. configurable: true
  12070. });
  12071. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12072. /**
  12073. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12074. */
  12075. get: function () {
  12076. return this._isStencilEnable;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Engine.prototype._prepareWorkingCanvas = function () {
  12082. if (this._workingCanvas) {
  12083. return;
  12084. }
  12085. this._workingCanvas = document.createElement("canvas");
  12086. var context = this._workingCanvas.getContext("2d");
  12087. if (context) {
  12088. this._workingContext = context;
  12089. }
  12090. };
  12091. /**
  12092. * Reset the texture cache to empty state
  12093. */
  12094. Engine.prototype.resetTextureCache = function () {
  12095. for (var key in this._boundTexturesCache) {
  12096. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12097. continue;
  12098. }
  12099. var boundTexture = this._boundTexturesCache[key];
  12100. if (boundTexture) {
  12101. this._removeDesignatedSlot(boundTexture);
  12102. }
  12103. this._boundTexturesCache[key] = null;
  12104. }
  12105. if (!this.disableTextureBindingOptimization) {
  12106. this._nextFreeTextureSlots = [];
  12107. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12108. this._nextFreeTextureSlots.push(slot);
  12109. }
  12110. }
  12111. this._currentTextureChannel = -1;
  12112. };
  12113. /**
  12114. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12115. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12116. * @returns true if engine is in deterministic lock step mode
  12117. */
  12118. Engine.prototype.isDeterministicLockStep = function () {
  12119. return this._deterministicLockstep;
  12120. };
  12121. /**
  12122. * Gets the max steps when engine is running in deterministic lock step
  12123. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12124. * @returns the max steps
  12125. */
  12126. Engine.prototype.getLockstepMaxSteps = function () {
  12127. return this._lockstepMaxSteps;
  12128. };
  12129. /**
  12130. * Gets an object containing information about the current webGL context
  12131. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12132. */
  12133. Engine.prototype.getGlInfo = function () {
  12134. return {
  12135. vendor: this._glVendor,
  12136. renderer: this._glRenderer,
  12137. version: this._glVersion
  12138. };
  12139. };
  12140. /**
  12141. * Gets current aspect ratio
  12142. * @param camera defines the camera to use to get the aspect ratio
  12143. * @param useScreen defines if screen size must be used (or the current render target if any)
  12144. * @returns a number defining the aspect ratio
  12145. */
  12146. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12147. if (useScreen === void 0) { useScreen = false; }
  12148. var viewport = camera.viewport;
  12149. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12150. };
  12151. /**
  12152. * Gets current screen aspect ratio
  12153. * @returns a number defining the aspect ratio
  12154. */
  12155. Engine.prototype.getScreenAspectRatio = function () {
  12156. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12157. };
  12158. /**
  12159. * Gets the current render width
  12160. * @param useScreen defines if screen size must be used (or the current render target if any)
  12161. * @returns a number defining the current render width
  12162. */
  12163. Engine.prototype.getRenderWidth = function (useScreen) {
  12164. if (useScreen === void 0) { useScreen = false; }
  12165. if (!useScreen && this._currentRenderTarget) {
  12166. return this._currentRenderTarget.width;
  12167. }
  12168. return this._gl.drawingBufferWidth;
  12169. };
  12170. /**
  12171. * Gets the current render height
  12172. * @param useScreen defines if screen size must be used (or the current render target if any)
  12173. * @returns a number defining the current render height
  12174. */
  12175. Engine.prototype.getRenderHeight = function (useScreen) {
  12176. if (useScreen === void 0) { useScreen = false; }
  12177. if (!useScreen && this._currentRenderTarget) {
  12178. return this._currentRenderTarget.height;
  12179. }
  12180. return this._gl.drawingBufferHeight;
  12181. };
  12182. /**
  12183. * Gets the HTML canvas attached with the current webGL context
  12184. * @returns a HTML canvas
  12185. */
  12186. Engine.prototype.getRenderingCanvas = function () {
  12187. return this._renderingCanvas;
  12188. };
  12189. /**
  12190. * Gets the client rect of the HTML canvas attached with the current webGL context
  12191. * @returns a client rectanglee
  12192. */
  12193. Engine.prototype.getRenderingCanvasClientRect = function () {
  12194. if (!this._renderingCanvas) {
  12195. return null;
  12196. }
  12197. return this._renderingCanvas.getBoundingClientRect();
  12198. };
  12199. /**
  12200. * Defines the hardware scaling level.
  12201. * By default the hardware scaling level is computed from the window device ratio.
  12202. * 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.
  12203. * @param level defines the level to use
  12204. */
  12205. Engine.prototype.setHardwareScalingLevel = function (level) {
  12206. this._hardwareScalingLevel = level;
  12207. this.resize();
  12208. };
  12209. /**
  12210. * Gets the current hardware scaling level.
  12211. * By default the hardware scaling level is computed from the window device ratio.
  12212. * 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.
  12213. * @returns a number indicating the current hardware scaling level
  12214. */
  12215. Engine.prototype.getHardwareScalingLevel = function () {
  12216. return this._hardwareScalingLevel;
  12217. };
  12218. /**
  12219. * Gets the list of loaded textures
  12220. * @returns an array containing all loaded textures
  12221. */
  12222. Engine.prototype.getLoadedTexturesCache = function () {
  12223. return this._internalTexturesCache;
  12224. };
  12225. /**
  12226. * Gets the object containing all engine capabilities
  12227. * @returns the EngineCapabilities object
  12228. */
  12229. Engine.prototype.getCaps = function () {
  12230. return this._caps;
  12231. };
  12232. Object.defineProperty(Engine.prototype, "drawCalls", {
  12233. /** @hidden */
  12234. get: function () {
  12235. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12236. return 0;
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12242. /** @hidden */
  12243. get: function () {
  12244. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12245. return null;
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. /**
  12251. * Gets the current depth function
  12252. * @returns a number defining the depth function
  12253. */
  12254. Engine.prototype.getDepthFunction = function () {
  12255. return this._depthCullingState.depthFunc;
  12256. };
  12257. /**
  12258. * Sets the current depth function
  12259. * @param depthFunc defines the function to use
  12260. */
  12261. Engine.prototype.setDepthFunction = function (depthFunc) {
  12262. this._depthCullingState.depthFunc = depthFunc;
  12263. };
  12264. /**
  12265. * Sets the current depth function to GREATER
  12266. */
  12267. Engine.prototype.setDepthFunctionToGreater = function () {
  12268. this._depthCullingState.depthFunc = this._gl.GREATER;
  12269. };
  12270. /**
  12271. * Sets the current depth function to GEQUAL
  12272. */
  12273. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12274. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12275. };
  12276. /**
  12277. * Sets the current depth function to LESS
  12278. */
  12279. Engine.prototype.setDepthFunctionToLess = function () {
  12280. this._depthCullingState.depthFunc = this._gl.LESS;
  12281. };
  12282. /**
  12283. * Sets the current depth function to LEQUAL
  12284. */
  12285. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12286. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12287. };
  12288. /**
  12289. * Gets a boolean indicating if stencil buffer is enabled
  12290. * @returns the current stencil buffer state
  12291. */
  12292. Engine.prototype.getStencilBuffer = function () {
  12293. return this._stencilState.stencilTest;
  12294. };
  12295. /**
  12296. * Enable or disable the stencil buffer
  12297. * @param enable defines if the stencil buffer must be enabled or disabled
  12298. */
  12299. Engine.prototype.setStencilBuffer = function (enable) {
  12300. this._stencilState.stencilTest = enable;
  12301. };
  12302. /**
  12303. * Gets the current stencil mask
  12304. * @returns a number defining the new stencil mask to use
  12305. */
  12306. Engine.prototype.getStencilMask = function () {
  12307. return this._stencilState.stencilMask;
  12308. };
  12309. /**
  12310. * Sets the current stencil mask
  12311. * @param mask defines the new stencil mask to use
  12312. */
  12313. Engine.prototype.setStencilMask = function (mask) {
  12314. this._stencilState.stencilMask = mask;
  12315. };
  12316. /**
  12317. * Gets the current stencil function
  12318. * @returns a number defining the stencil function to use
  12319. */
  12320. Engine.prototype.getStencilFunction = function () {
  12321. return this._stencilState.stencilFunc;
  12322. };
  12323. /**
  12324. * Gets the current stencil reference value
  12325. * @returns a number defining the stencil reference value to use
  12326. */
  12327. Engine.prototype.getStencilFunctionReference = function () {
  12328. return this._stencilState.stencilFuncRef;
  12329. };
  12330. /**
  12331. * Gets the current stencil mask
  12332. * @returns a number defining the stencil mask to use
  12333. */
  12334. Engine.prototype.getStencilFunctionMask = function () {
  12335. return this._stencilState.stencilFuncMask;
  12336. };
  12337. /**
  12338. * Sets the current stencil function
  12339. * @param stencilFunc defines the new stencil function to use
  12340. */
  12341. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12342. this._stencilState.stencilFunc = stencilFunc;
  12343. };
  12344. /**
  12345. * Sets the current stencil reference
  12346. * @param reference defines the new stencil reference to use
  12347. */
  12348. Engine.prototype.setStencilFunctionReference = function (reference) {
  12349. this._stencilState.stencilFuncRef = reference;
  12350. };
  12351. /**
  12352. * Sets the current stencil mask
  12353. * @param mask defines the new stencil mask to use
  12354. */
  12355. Engine.prototype.setStencilFunctionMask = function (mask) {
  12356. this._stencilState.stencilFuncMask = mask;
  12357. };
  12358. /**
  12359. * Gets the current stencil operation when stencil fails
  12360. * @returns a number defining stencil operation to use when stencil fails
  12361. */
  12362. Engine.prototype.getStencilOperationFail = function () {
  12363. return this._stencilState.stencilOpStencilFail;
  12364. };
  12365. /**
  12366. * Gets the current stencil operation when depth fails
  12367. * @returns a number defining stencil operation to use when depth fails
  12368. */
  12369. Engine.prototype.getStencilOperationDepthFail = function () {
  12370. return this._stencilState.stencilOpDepthFail;
  12371. };
  12372. /**
  12373. * Gets the current stencil operation when stencil passes
  12374. * @returns a number defining stencil operation to use when stencil passes
  12375. */
  12376. Engine.prototype.getStencilOperationPass = function () {
  12377. return this._stencilState.stencilOpStencilDepthPass;
  12378. };
  12379. /**
  12380. * Sets the stencil operation to use when stencil fails
  12381. * @param operation defines the stencil operation to use when stencil fails
  12382. */
  12383. Engine.prototype.setStencilOperationFail = function (operation) {
  12384. this._stencilState.stencilOpStencilFail = operation;
  12385. };
  12386. /**
  12387. * Sets the stencil operation to use when depth fails
  12388. * @param operation defines the stencil operation to use when depth fails
  12389. */
  12390. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12391. this._stencilState.stencilOpDepthFail = operation;
  12392. };
  12393. /**
  12394. * Sets the stencil operation to use when stencil passes
  12395. * @param operation defines the stencil operation to use when stencil passes
  12396. */
  12397. Engine.prototype.setStencilOperationPass = function (operation) {
  12398. this._stencilState.stencilOpStencilDepthPass = operation;
  12399. };
  12400. /**
  12401. * Sets a boolean indicating if the dithering state is enabled or disabled
  12402. * @param value defines the dithering state
  12403. */
  12404. Engine.prototype.setDitheringState = function (value) {
  12405. if (value) {
  12406. this._gl.enable(this._gl.DITHER);
  12407. }
  12408. else {
  12409. this._gl.disable(this._gl.DITHER);
  12410. }
  12411. };
  12412. /**
  12413. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12414. * @param value defines the rasterizer state
  12415. */
  12416. Engine.prototype.setRasterizerState = function (value) {
  12417. if (value) {
  12418. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12419. }
  12420. else {
  12421. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12422. }
  12423. };
  12424. /**
  12425. * stop executing a render loop function and remove it from the execution array
  12426. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12427. */
  12428. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12429. if (!renderFunction) {
  12430. this._activeRenderLoops = [];
  12431. return;
  12432. }
  12433. var index = this._activeRenderLoops.indexOf(renderFunction);
  12434. if (index >= 0) {
  12435. this._activeRenderLoops.splice(index, 1);
  12436. }
  12437. };
  12438. /** @hidden */
  12439. Engine.prototype._renderLoop = function () {
  12440. if (!this._contextWasLost) {
  12441. var shouldRender = true;
  12442. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12443. shouldRender = false;
  12444. }
  12445. if (shouldRender) {
  12446. // Start new frame
  12447. this.beginFrame();
  12448. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12449. var renderFunction = this._activeRenderLoops[index];
  12450. renderFunction();
  12451. }
  12452. // Present
  12453. this.endFrame();
  12454. }
  12455. }
  12456. if (this._activeRenderLoops.length > 0) {
  12457. // Register new frame
  12458. var requester = null;
  12459. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12460. requester = this._vrDisplay;
  12461. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12462. }
  12463. else {
  12464. this._renderingQueueLaunched = false;
  12465. }
  12466. };
  12467. /**
  12468. * Register and execute a render loop. The engine can have more than one render function
  12469. * @param renderFunction defines the function to continuously execute
  12470. */
  12471. Engine.prototype.runRenderLoop = function (renderFunction) {
  12472. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12473. return;
  12474. }
  12475. this._activeRenderLoops.push(renderFunction);
  12476. if (!this._renderingQueueLaunched) {
  12477. this._renderingQueueLaunched = true;
  12478. this._bindedRenderFunction = this._renderLoop.bind(this);
  12479. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12480. }
  12481. };
  12482. /**
  12483. * Toggle full screen mode
  12484. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12485. * @param options defines an option object to be sent to the requestFullscreen function
  12486. */
  12487. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12488. if (this.isFullscreen) {
  12489. BABYLON.Tools.ExitFullscreen();
  12490. }
  12491. else {
  12492. this._pointerLockRequested = requestPointerLock;
  12493. if (this._renderingCanvas) {
  12494. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12495. }
  12496. }
  12497. };
  12498. /**
  12499. * Clear the current render buffer or the current render target (if any is set up)
  12500. * @param color defines the color to use
  12501. * @param backBuffer defines if the back buffer must be cleared
  12502. * @param depth defines if the depth buffer must be cleared
  12503. * @param stencil defines if the stencil buffer must be cleared
  12504. */
  12505. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12506. if (stencil === void 0) { stencil = false; }
  12507. this.applyStates();
  12508. var mode = 0;
  12509. if (backBuffer && color) {
  12510. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12511. mode |= this._gl.COLOR_BUFFER_BIT;
  12512. }
  12513. if (depth) {
  12514. this._gl.clearDepth(1.0);
  12515. mode |= this._gl.DEPTH_BUFFER_BIT;
  12516. }
  12517. if (stencil) {
  12518. this._gl.clearStencil(0);
  12519. mode |= this._gl.STENCIL_BUFFER_BIT;
  12520. }
  12521. this._gl.clear(mode);
  12522. };
  12523. /**
  12524. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12525. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12526. * @param y defines the y-coordinate of the corner of the clear rectangle
  12527. * @param width defines the width of the clear rectangle
  12528. * @param height defines the height of the clear rectangle
  12529. * @param clearColor defines the clear color
  12530. */
  12531. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12532. var gl = this._gl;
  12533. // Save state
  12534. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12535. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12536. // Change state
  12537. gl.enable(gl.SCISSOR_TEST);
  12538. gl.scissor(x, y, width, height);
  12539. // Clear
  12540. this.clear(clearColor, true, true, true);
  12541. // Restore state
  12542. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12543. if (curScissor === true) {
  12544. gl.enable(gl.SCISSOR_TEST);
  12545. }
  12546. else {
  12547. gl.disable(gl.SCISSOR_TEST);
  12548. }
  12549. };
  12550. /** @hidden */
  12551. Engine.prototype._viewport = function (x, y, width, height) {
  12552. if (x !== this._viewportCached.x ||
  12553. y !== this._viewportCached.y ||
  12554. width !== this._viewportCached.z ||
  12555. height !== this._viewportCached.w) {
  12556. this._viewportCached.x = x;
  12557. this._viewportCached.y = y;
  12558. this._viewportCached.z = width;
  12559. this._viewportCached.w = height;
  12560. this._gl.viewport(x, y, width, height);
  12561. }
  12562. };
  12563. /**
  12564. * Set the WebGL's viewport
  12565. * @param viewport defines the viewport element to be used
  12566. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12567. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12568. */
  12569. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12570. var width = requiredWidth || this.getRenderWidth();
  12571. var height = requiredHeight || this.getRenderHeight();
  12572. var x = viewport.x || 0;
  12573. var y = viewport.y || 0;
  12574. this._cachedViewport = viewport;
  12575. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12576. };
  12577. /**
  12578. * Directly set the WebGL Viewport
  12579. * @param x defines the x coordinate of the viewport (in screen space)
  12580. * @param y defines the y coordinate of the viewport (in screen space)
  12581. * @param width defines the width of the viewport (in screen space)
  12582. * @param height defines the height of the viewport (in screen space)
  12583. * @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
  12584. */
  12585. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12586. var currentViewport = this._cachedViewport;
  12587. this._cachedViewport = null;
  12588. this._viewport(x, y, width, height);
  12589. return currentViewport;
  12590. };
  12591. /**
  12592. * Begin a new frame
  12593. */
  12594. Engine.prototype.beginFrame = function () {
  12595. this.onBeginFrameObservable.notifyObservers(this);
  12596. this._measureFps();
  12597. };
  12598. /**
  12599. * Enf the current frame
  12600. */
  12601. Engine.prototype.endFrame = function () {
  12602. // Force a flush in case we are using a bad OS.
  12603. if (this._badOS) {
  12604. this.flushFramebuffer();
  12605. }
  12606. // Submit frame to the vr device, if enabled
  12607. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12608. // TODO: We should only submit the frame if we read frameData successfully.
  12609. this._vrDisplay.submitFrame();
  12610. }
  12611. this.onEndFrameObservable.notifyObservers(this);
  12612. };
  12613. /**
  12614. * Resize the view according to the canvas' size
  12615. */
  12616. Engine.prototype.resize = function () {
  12617. // We're not resizing the size of the canvas while in VR mode & presenting
  12618. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12619. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12620. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12621. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12622. }
  12623. };
  12624. /**
  12625. * Force a specific size of the canvas
  12626. * @param width defines the new canvas' width
  12627. * @param height defines the new canvas' height
  12628. */
  12629. Engine.prototype.setSize = function (width, height) {
  12630. if (!this._renderingCanvas) {
  12631. return;
  12632. }
  12633. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12634. return;
  12635. }
  12636. this._renderingCanvas.width = width;
  12637. this._renderingCanvas.height = height;
  12638. for (var index = 0; index < this.scenes.length; index++) {
  12639. var scene = this.scenes[index];
  12640. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12641. var cam = scene.cameras[camIndex];
  12642. cam._currentRenderId = 0;
  12643. }
  12644. }
  12645. if (this.onResizeObservable.hasObservers) {
  12646. this.onResizeObservable.notifyObservers(this);
  12647. }
  12648. };
  12649. // WebVR functions
  12650. /**
  12651. * Gets a boolean indicating if a webVR device was detected
  12652. * @returns true if a webVR device was detected
  12653. */
  12654. Engine.prototype.isVRDevicePresent = function () {
  12655. return !!this._vrDisplay;
  12656. };
  12657. /**
  12658. * Gets the current webVR device
  12659. * @returns the current webVR device (or null)
  12660. */
  12661. Engine.prototype.getVRDevice = function () {
  12662. return this._vrDisplay;
  12663. };
  12664. /**
  12665. * Initializes a webVR display and starts listening to display change events
  12666. * The onVRDisplayChangedObservable will be notified upon these changes
  12667. * @returns The onVRDisplayChangedObservable
  12668. */
  12669. Engine.prototype.initWebVR = function () {
  12670. this.initWebVRAsync();
  12671. return this.onVRDisplayChangedObservable;
  12672. };
  12673. /**
  12674. * Initializes a webVR display and starts listening to display change events
  12675. * The onVRDisplayChangedObservable will be notified upon these changes
  12676. * @returns A promise containing a VRDisplay and if vr is supported
  12677. */
  12678. Engine.prototype.initWebVRAsync = function () {
  12679. var _this = this;
  12680. var notifyObservers = function () {
  12681. var eventArgs = {
  12682. vrDisplay: _this._vrDisplay,
  12683. vrSupported: _this._vrSupported
  12684. };
  12685. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12686. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12687. };
  12688. if (!this._onVrDisplayConnect) {
  12689. this._onVrDisplayConnect = function (event) {
  12690. _this._vrDisplay = event.display;
  12691. notifyObservers();
  12692. };
  12693. this._onVrDisplayDisconnect = function () {
  12694. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12695. _this._vrDisplay = undefined;
  12696. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12697. notifyObservers();
  12698. };
  12699. this._onVrDisplayPresentChange = function () {
  12700. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12701. };
  12702. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12703. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12704. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12705. }
  12706. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12707. this._webVRInitPromise.then(notifyObservers);
  12708. return this._webVRInitPromise;
  12709. };
  12710. /**
  12711. * Call this function to switch to webVR mode
  12712. * Will do nothing if webVR is not supported or if there is no webVR device
  12713. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12714. */
  12715. Engine.prototype.enableVR = function () {
  12716. var _this = this;
  12717. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12718. var onResolved = function () {
  12719. _this.onVRRequestPresentComplete.notifyObservers(true);
  12720. _this._onVRFullScreenTriggered();
  12721. };
  12722. var onRejected = function () {
  12723. _this.onVRRequestPresentComplete.notifyObservers(false);
  12724. };
  12725. this.onVRRequestPresentStart.notifyObservers(this);
  12726. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12727. }
  12728. };
  12729. /**
  12730. * Call this function to leave webVR mode
  12731. * Will do nothing if webVR is not supported or if there is no webVR device
  12732. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12733. */
  12734. Engine.prototype.disableVR = function () {
  12735. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12736. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12737. }
  12738. };
  12739. Engine.prototype._getVRDisplaysAsync = function () {
  12740. var _this = this;
  12741. return new Promise(function (res, rej) {
  12742. if (navigator.getVRDisplays) {
  12743. navigator.getVRDisplays().then(function (devices) {
  12744. _this._vrSupported = true;
  12745. // note that devices may actually be an empty array. This is fine;
  12746. // we expect this._vrDisplay to be undefined in this case.
  12747. _this._vrDisplay = devices[0];
  12748. res({
  12749. vrDisplay: _this._vrDisplay,
  12750. vrSupported: _this._vrSupported
  12751. });
  12752. });
  12753. }
  12754. else {
  12755. _this._vrDisplay = undefined;
  12756. _this._vrSupported = false;
  12757. res({
  12758. vrDisplay: _this._vrDisplay,
  12759. vrSupported: _this._vrSupported
  12760. });
  12761. }
  12762. });
  12763. };
  12764. /**
  12765. * Binds the frame buffer to the specified texture.
  12766. * @param texture The texture to render to or null for the default canvas
  12767. * @param faceIndex The face of the texture to render to in case of cube texture
  12768. * @param requiredWidth The width of the target to render to
  12769. * @param requiredHeight The height of the target to render to
  12770. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12771. * @param depthStencilTexture The depth stencil texture to use to render
  12772. * @param lodLevel defines le lod level to bind to the frame buffer
  12773. */
  12774. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12775. if (lodLevel === void 0) { lodLevel = 0; }
  12776. if (this._currentRenderTarget) {
  12777. this.unBindFramebuffer(this._currentRenderTarget);
  12778. }
  12779. this._currentRenderTarget = texture;
  12780. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12781. var gl = this._gl;
  12782. if (texture.isCube) {
  12783. if (faceIndex === undefined) {
  12784. faceIndex = 0;
  12785. }
  12786. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12787. if (depthStencilTexture) {
  12788. if (depthStencilTexture._generateStencilBuffer) {
  12789. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12790. }
  12791. else {
  12792. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12793. }
  12794. }
  12795. }
  12796. if (this._cachedViewport && !forceFullscreenViewport) {
  12797. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12798. }
  12799. else {
  12800. if (!requiredWidth) {
  12801. requiredWidth = texture.width;
  12802. if (lodLevel) {
  12803. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12804. }
  12805. }
  12806. if (!requiredHeight) {
  12807. requiredHeight = texture.height;
  12808. if (lodLevel) {
  12809. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12810. }
  12811. }
  12812. this._viewport(0, 0, requiredWidth, requiredHeight);
  12813. }
  12814. this.wipeCaches();
  12815. };
  12816. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12817. if (this._currentFramebuffer !== framebuffer) {
  12818. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12819. this._currentFramebuffer = framebuffer;
  12820. }
  12821. };
  12822. /**
  12823. * Unbind the current render target texture from the webGL context
  12824. * @param texture defines the render target texture to unbind
  12825. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12826. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12827. */
  12828. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12829. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12830. this._currentRenderTarget = null;
  12831. // If MSAA, we need to bitblt back to main texture
  12832. var gl = this._gl;
  12833. if (texture._MSAAFramebuffer) {
  12834. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12835. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12836. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12837. }
  12838. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12839. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12840. gl.generateMipmap(gl.TEXTURE_2D);
  12841. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12842. }
  12843. if (onBeforeUnbind) {
  12844. if (texture._MSAAFramebuffer) {
  12845. // Bind the correct framebuffer
  12846. this.bindUnboundFramebuffer(texture._framebuffer);
  12847. }
  12848. onBeforeUnbind();
  12849. }
  12850. this.bindUnboundFramebuffer(null);
  12851. };
  12852. /**
  12853. * Unbind a list of render target textures from the webGL context
  12854. * This is used only when drawBuffer extension or webGL2 are active
  12855. * @param textures defines the render target textures to unbind
  12856. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12857. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12858. */
  12859. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12860. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12861. this._currentRenderTarget = null;
  12862. // If MSAA, we need to bitblt back to main texture
  12863. var gl = this._gl;
  12864. if (textures[0]._MSAAFramebuffer) {
  12865. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12866. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12867. var attachments = textures[0]._attachments;
  12868. if (!attachments) {
  12869. attachments = new Array(textures.length);
  12870. textures[0]._attachments = attachments;
  12871. }
  12872. for (var i = 0; i < textures.length; i++) {
  12873. var texture = textures[i];
  12874. for (var j = 0; j < attachments.length; j++) {
  12875. attachments[j] = gl.NONE;
  12876. }
  12877. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12878. gl.readBuffer(attachments[i]);
  12879. gl.drawBuffers(attachments);
  12880. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12881. }
  12882. for (var i = 0; i < attachments.length; i++) {
  12883. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12884. }
  12885. gl.drawBuffers(attachments);
  12886. }
  12887. for (var i = 0; i < textures.length; i++) {
  12888. var texture = textures[i];
  12889. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12890. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12891. gl.generateMipmap(gl.TEXTURE_2D);
  12892. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12893. }
  12894. }
  12895. if (onBeforeUnbind) {
  12896. if (textures[0]._MSAAFramebuffer) {
  12897. // Bind the correct framebuffer
  12898. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12899. }
  12900. onBeforeUnbind();
  12901. }
  12902. this.bindUnboundFramebuffer(null);
  12903. };
  12904. /**
  12905. * Force the mipmap generation for the given render target texture
  12906. * @param texture defines the render target texture to use
  12907. */
  12908. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12909. if (texture.generateMipMaps) {
  12910. var gl = this._gl;
  12911. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12912. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12913. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12914. }
  12915. };
  12916. /**
  12917. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12918. */
  12919. Engine.prototype.flushFramebuffer = function () {
  12920. this._gl.flush();
  12921. };
  12922. /**
  12923. * Unbind the current render target and bind the default framebuffer
  12924. */
  12925. Engine.prototype.restoreDefaultFramebuffer = function () {
  12926. if (this._currentRenderTarget) {
  12927. this.unBindFramebuffer(this._currentRenderTarget);
  12928. }
  12929. else {
  12930. this.bindUnboundFramebuffer(null);
  12931. }
  12932. if (this._cachedViewport) {
  12933. this.setViewport(this._cachedViewport);
  12934. }
  12935. this.wipeCaches();
  12936. };
  12937. // UBOs
  12938. /**
  12939. * Create an uniform buffer
  12940. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12941. * @param elements defines the content of the uniform buffer
  12942. * @returns the webGL uniform buffer
  12943. */
  12944. Engine.prototype.createUniformBuffer = function (elements) {
  12945. var ubo = this._gl.createBuffer();
  12946. if (!ubo) {
  12947. throw new Error("Unable to create uniform buffer");
  12948. }
  12949. this.bindUniformBuffer(ubo);
  12950. if (elements instanceof Float32Array) {
  12951. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12952. }
  12953. else {
  12954. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12955. }
  12956. this.bindUniformBuffer(null);
  12957. ubo.references = 1;
  12958. return ubo;
  12959. };
  12960. /**
  12961. * Create a dynamic uniform buffer
  12962. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12963. * @param elements defines the content of the uniform buffer
  12964. * @returns the webGL uniform buffer
  12965. */
  12966. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12967. var ubo = this._gl.createBuffer();
  12968. if (!ubo) {
  12969. throw new Error("Unable to create dynamic uniform buffer");
  12970. }
  12971. this.bindUniformBuffer(ubo);
  12972. if (elements instanceof Float32Array) {
  12973. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12974. }
  12975. else {
  12976. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12977. }
  12978. this.bindUniformBuffer(null);
  12979. ubo.references = 1;
  12980. return ubo;
  12981. };
  12982. /**
  12983. * Update an existing uniform buffer
  12984. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12985. * @param uniformBuffer defines the target uniform buffer
  12986. * @param elements defines the content to update
  12987. * @param offset defines the offset in the uniform buffer where update should start
  12988. * @param count defines the size of the data to update
  12989. */
  12990. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12991. this.bindUniformBuffer(uniformBuffer);
  12992. if (offset === undefined) {
  12993. offset = 0;
  12994. }
  12995. if (count === undefined) {
  12996. if (elements instanceof Float32Array) {
  12997. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12998. }
  12999. else {
  13000. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13001. }
  13002. }
  13003. else {
  13004. if (elements instanceof Float32Array) {
  13005. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13006. }
  13007. else {
  13008. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13009. }
  13010. }
  13011. this.bindUniformBuffer(null);
  13012. };
  13013. // VBOs
  13014. Engine.prototype._resetVertexBufferBinding = function () {
  13015. this.bindArrayBuffer(null);
  13016. this._cachedVertexBuffers = null;
  13017. };
  13018. /**
  13019. * Creates a vertex buffer
  13020. * @param data the data for the vertex buffer
  13021. * @returns the new WebGL static buffer
  13022. */
  13023. Engine.prototype.createVertexBuffer = function (data) {
  13024. var vbo = this._gl.createBuffer();
  13025. if (!vbo) {
  13026. throw new Error("Unable to create vertex buffer");
  13027. }
  13028. this.bindArrayBuffer(vbo);
  13029. if (data instanceof Array) {
  13030. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13031. }
  13032. else {
  13033. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13034. }
  13035. this._resetVertexBufferBinding();
  13036. vbo.references = 1;
  13037. return vbo;
  13038. };
  13039. /**
  13040. * Creates a dynamic vertex buffer
  13041. * @param data the data for the dynamic vertex buffer
  13042. * @returns the new WebGL dynamic buffer
  13043. */
  13044. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13045. var vbo = this._gl.createBuffer();
  13046. if (!vbo) {
  13047. throw new Error("Unable to create dynamic vertex buffer");
  13048. }
  13049. this.bindArrayBuffer(vbo);
  13050. if (data instanceof Array) {
  13051. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13052. }
  13053. else {
  13054. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13055. }
  13056. this._resetVertexBufferBinding();
  13057. vbo.references = 1;
  13058. return vbo;
  13059. };
  13060. /**
  13061. * Update a dynamic index buffer
  13062. * @param indexBuffer defines the target index buffer
  13063. * @param indices defines the data to update
  13064. * @param offset defines the offset in the target index buffer where update should start
  13065. */
  13066. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13067. if (offset === void 0) { offset = 0; }
  13068. // Force cache update
  13069. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13070. this.bindIndexBuffer(indexBuffer);
  13071. var arrayBuffer;
  13072. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13073. arrayBuffer = indices;
  13074. }
  13075. else {
  13076. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13077. }
  13078. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13079. this._resetIndexBufferBinding();
  13080. };
  13081. /**
  13082. * Updates a dynamic vertex buffer.
  13083. * @param vertexBuffer the vertex buffer to update
  13084. * @param data the data used to update the vertex buffer
  13085. * @param byteOffset the byte offset of the data
  13086. * @param byteLength the byte length of the data
  13087. */
  13088. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13089. this.bindArrayBuffer(vertexBuffer);
  13090. if (byteOffset === undefined) {
  13091. byteOffset = 0;
  13092. }
  13093. if (byteLength === undefined) {
  13094. if (data instanceof Array) {
  13095. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13096. }
  13097. else {
  13098. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13099. }
  13100. }
  13101. else {
  13102. if (data instanceof Array) {
  13103. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13104. }
  13105. else {
  13106. if (data instanceof ArrayBuffer) {
  13107. data = new Uint8Array(data, byteOffset, byteLength);
  13108. }
  13109. else {
  13110. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13111. }
  13112. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13113. }
  13114. }
  13115. this._resetVertexBufferBinding();
  13116. };
  13117. Engine.prototype._resetIndexBufferBinding = function () {
  13118. this.bindIndexBuffer(null);
  13119. this._cachedIndexBuffer = null;
  13120. };
  13121. /**
  13122. * Creates a new index buffer
  13123. * @param indices defines the content of the index buffer
  13124. * @param updatable defines if the index buffer must be updatable
  13125. * @returns a new webGL buffer
  13126. */
  13127. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13128. var vbo = this._gl.createBuffer();
  13129. if (!vbo) {
  13130. throw new Error("Unable to create index buffer");
  13131. }
  13132. this.bindIndexBuffer(vbo);
  13133. // Check for 32 bits indices
  13134. var arrayBuffer;
  13135. var need32Bits = false;
  13136. if (indices instanceof Uint16Array) {
  13137. arrayBuffer = indices;
  13138. }
  13139. else {
  13140. //check 32 bit support
  13141. if (this._caps.uintIndices) {
  13142. if (indices instanceof Uint32Array) {
  13143. arrayBuffer = indices;
  13144. need32Bits = true;
  13145. }
  13146. else {
  13147. //number[] or Int32Array, check if 32 bit is necessary
  13148. for (var index = 0; index < indices.length; index++) {
  13149. if (indices[index] > 65535) {
  13150. need32Bits = true;
  13151. break;
  13152. }
  13153. }
  13154. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13155. }
  13156. }
  13157. else {
  13158. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13159. arrayBuffer = new Uint16Array(indices);
  13160. }
  13161. }
  13162. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13163. this._resetIndexBufferBinding();
  13164. vbo.references = 1;
  13165. vbo.is32Bits = need32Bits;
  13166. return vbo;
  13167. };
  13168. /**
  13169. * Bind a webGL buffer to the webGL context
  13170. * @param buffer defines the buffer to bind
  13171. */
  13172. Engine.prototype.bindArrayBuffer = function (buffer) {
  13173. if (!this._vaoRecordInProgress) {
  13174. this._unbindVertexArrayObject();
  13175. }
  13176. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13177. };
  13178. /**
  13179. * Bind an uniform buffer to the current webGL context
  13180. * @param buffer defines the buffer to bind
  13181. */
  13182. Engine.prototype.bindUniformBuffer = function (buffer) {
  13183. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13184. };
  13185. /**
  13186. * Bind a buffer to the current webGL context at a given location
  13187. * @param buffer defines the buffer to bind
  13188. * @param location defines the index where to bind the buffer
  13189. */
  13190. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13191. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13192. };
  13193. /**
  13194. * Bind a specific block at a given index in a specific shader program
  13195. * @param shaderProgram defines the shader program
  13196. * @param blockName defines the block name
  13197. * @param index defines the index where to bind the block
  13198. */
  13199. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13200. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13201. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13202. };
  13203. ;
  13204. Engine.prototype.bindIndexBuffer = function (buffer) {
  13205. if (!this._vaoRecordInProgress) {
  13206. this._unbindVertexArrayObject();
  13207. }
  13208. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13209. };
  13210. Engine.prototype.bindBuffer = function (buffer, target) {
  13211. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13212. this._gl.bindBuffer(target, buffer);
  13213. this._currentBoundBuffer[target] = buffer;
  13214. }
  13215. };
  13216. /**
  13217. * update the bound buffer with the given data
  13218. * @param data defines the data to update
  13219. */
  13220. Engine.prototype.updateArrayBuffer = function (data) {
  13221. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13222. };
  13223. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13224. var pointer = this._currentBufferPointers[indx];
  13225. var changed = false;
  13226. if (!pointer.active) {
  13227. changed = true;
  13228. pointer.active = true;
  13229. pointer.index = indx;
  13230. pointer.size = size;
  13231. pointer.type = type;
  13232. pointer.normalized = normalized;
  13233. pointer.stride = stride;
  13234. pointer.offset = offset;
  13235. pointer.buffer = buffer;
  13236. }
  13237. else {
  13238. if (pointer.buffer !== buffer) {
  13239. pointer.buffer = buffer;
  13240. changed = true;
  13241. }
  13242. if (pointer.size !== size) {
  13243. pointer.size = size;
  13244. changed = true;
  13245. }
  13246. if (pointer.type !== type) {
  13247. pointer.type = type;
  13248. changed = true;
  13249. }
  13250. if (pointer.normalized !== normalized) {
  13251. pointer.normalized = normalized;
  13252. changed = true;
  13253. }
  13254. if (pointer.stride !== stride) {
  13255. pointer.stride = stride;
  13256. changed = true;
  13257. }
  13258. if (pointer.offset !== offset) {
  13259. pointer.offset = offset;
  13260. changed = true;
  13261. }
  13262. }
  13263. if (changed || this._vaoRecordInProgress) {
  13264. this.bindArrayBuffer(buffer);
  13265. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13266. }
  13267. };
  13268. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13269. if (indexBuffer == null) {
  13270. return;
  13271. }
  13272. if (this._cachedIndexBuffer !== indexBuffer) {
  13273. this._cachedIndexBuffer = indexBuffer;
  13274. this.bindIndexBuffer(indexBuffer);
  13275. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13276. }
  13277. };
  13278. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13279. var attributes = effect.getAttributesNames();
  13280. if (!this._vaoRecordInProgress) {
  13281. this._unbindVertexArrayObject();
  13282. }
  13283. this.unbindAllAttributes();
  13284. for (var index = 0; index < attributes.length; index++) {
  13285. var order = effect.getAttributeLocation(index);
  13286. if (order >= 0) {
  13287. var vertexBuffer = vertexBuffers[attributes[index]];
  13288. if (!vertexBuffer) {
  13289. continue;
  13290. }
  13291. this._gl.enableVertexAttribArray(order);
  13292. if (!this._vaoRecordInProgress) {
  13293. this._vertexAttribArraysEnabled[order] = true;
  13294. }
  13295. var buffer = vertexBuffer.getBuffer();
  13296. if (buffer) {
  13297. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13298. if (vertexBuffer.getIsInstanced()) {
  13299. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13300. if (!this._vaoRecordInProgress) {
  13301. this._currentInstanceLocations.push(order);
  13302. this._currentInstanceBuffers.push(buffer);
  13303. }
  13304. }
  13305. }
  13306. }
  13307. }
  13308. };
  13309. /**
  13310. * Records a vertex array object
  13311. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13312. * @param vertexBuffers defines the list of vertex buffers to store
  13313. * @param indexBuffer defines the index buffer to store
  13314. * @param effect defines the effect to store
  13315. * @returns the new vertex array object
  13316. */
  13317. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13318. var vao = this._gl.createVertexArray();
  13319. this._vaoRecordInProgress = true;
  13320. this._gl.bindVertexArray(vao);
  13321. this._mustWipeVertexAttributes = true;
  13322. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13323. this.bindIndexBuffer(indexBuffer);
  13324. this._vaoRecordInProgress = false;
  13325. this._gl.bindVertexArray(null);
  13326. return vao;
  13327. };
  13328. /**
  13329. * Bind a specific vertex array object
  13330. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13331. * @param vertexArrayObject defines the vertex array object to bind
  13332. * @param indexBuffer defines the index buffer to bind
  13333. */
  13334. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13335. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13336. this._cachedVertexArrayObject = vertexArrayObject;
  13337. this._gl.bindVertexArray(vertexArrayObject);
  13338. this._cachedVertexBuffers = null;
  13339. this._cachedIndexBuffer = null;
  13340. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13341. this._mustWipeVertexAttributes = true;
  13342. }
  13343. };
  13344. /**
  13345. * Bind webGl buffers directly to the webGL context
  13346. * @param vertexBuffer defines the vertex buffer to bind
  13347. * @param indexBuffer defines the index buffer to bind
  13348. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13349. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13350. * @param effect defines the effect associated with the vertex buffer
  13351. */
  13352. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13353. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13354. this._cachedVertexBuffers = vertexBuffer;
  13355. this._cachedEffectForVertexBuffers = effect;
  13356. var attributesCount = effect.getAttributesCount();
  13357. this._unbindVertexArrayObject();
  13358. this.unbindAllAttributes();
  13359. var offset = 0;
  13360. for (var index = 0; index < attributesCount; index++) {
  13361. if (index < vertexDeclaration.length) {
  13362. var order = effect.getAttributeLocation(index);
  13363. if (order >= 0) {
  13364. this._gl.enableVertexAttribArray(order);
  13365. this._vertexAttribArraysEnabled[order] = true;
  13366. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13367. }
  13368. offset += vertexDeclaration[index] * 4;
  13369. }
  13370. }
  13371. }
  13372. this._bindIndexBufferWithCache(indexBuffer);
  13373. };
  13374. Engine.prototype._unbindVertexArrayObject = function () {
  13375. if (!this._cachedVertexArrayObject) {
  13376. return;
  13377. }
  13378. this._cachedVertexArrayObject = null;
  13379. this._gl.bindVertexArray(null);
  13380. };
  13381. /**
  13382. * Bind a list of vertex buffers to the webGL context
  13383. * @param vertexBuffers defines the list of vertex buffers to bind
  13384. * @param indexBuffer defines the index buffer to bind
  13385. * @param effect defines the effect associated with the vertex buffers
  13386. */
  13387. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13388. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13389. this._cachedVertexBuffers = vertexBuffers;
  13390. this._cachedEffectForVertexBuffers = effect;
  13391. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13392. }
  13393. this._bindIndexBufferWithCache(indexBuffer);
  13394. };
  13395. /**
  13396. * Unbind all instance attributes
  13397. */
  13398. Engine.prototype.unbindInstanceAttributes = function () {
  13399. var boundBuffer;
  13400. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13401. var instancesBuffer = this._currentInstanceBuffers[i];
  13402. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13403. boundBuffer = instancesBuffer;
  13404. this.bindArrayBuffer(instancesBuffer);
  13405. }
  13406. var offsetLocation = this._currentInstanceLocations[i];
  13407. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13408. }
  13409. this._currentInstanceBuffers.length = 0;
  13410. this._currentInstanceLocations.length = 0;
  13411. };
  13412. /**
  13413. * Release and free the memory of a vertex array object
  13414. * @param vao defines the vertex array object to delete
  13415. */
  13416. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13417. this._gl.deleteVertexArray(vao);
  13418. };
  13419. /** @hidden */
  13420. Engine.prototype._releaseBuffer = function (buffer) {
  13421. buffer.references--;
  13422. if (buffer.references === 0) {
  13423. this._gl.deleteBuffer(buffer);
  13424. return true;
  13425. }
  13426. return false;
  13427. };
  13428. /**
  13429. * Creates a webGL buffer to use with instanciation
  13430. * @param capacity defines the size of the buffer
  13431. * @returns the webGL buffer
  13432. */
  13433. Engine.prototype.createInstancesBuffer = function (capacity) {
  13434. var buffer = this._gl.createBuffer();
  13435. if (!buffer) {
  13436. throw new Error("Unable to create instance buffer");
  13437. }
  13438. buffer.capacity = capacity;
  13439. this.bindArrayBuffer(buffer);
  13440. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13441. return buffer;
  13442. };
  13443. /**
  13444. * Delete a webGL buffer used with instanciation
  13445. * @param buffer defines the webGL buffer to delete
  13446. */
  13447. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13448. this._gl.deleteBuffer(buffer);
  13449. };
  13450. /**
  13451. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13452. * @param instancesBuffer defines the webGL buffer to update and bind
  13453. * @param data defines the data to store in the buffer
  13454. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13455. */
  13456. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13457. this.bindArrayBuffer(instancesBuffer);
  13458. if (data) {
  13459. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13460. }
  13461. if (offsetLocations[0].index !== undefined) {
  13462. var stride = 0;
  13463. for (var i = 0; i < offsetLocations.length; i++) {
  13464. var ai = offsetLocations[i];
  13465. stride += ai.attributeSize * 4;
  13466. }
  13467. for (var i = 0; i < offsetLocations.length; i++) {
  13468. var ai = offsetLocations[i];
  13469. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13470. this._gl.enableVertexAttribArray(ai.index);
  13471. this._vertexAttribArraysEnabled[ai.index] = true;
  13472. }
  13473. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13474. this._gl.vertexAttribDivisor(ai.index, 1);
  13475. this._currentInstanceLocations.push(ai.index);
  13476. this._currentInstanceBuffers.push(instancesBuffer);
  13477. }
  13478. }
  13479. else {
  13480. for (var index = 0; index < 4; index++) {
  13481. var offsetLocation = offsetLocations[index];
  13482. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13483. this._gl.enableVertexAttribArray(offsetLocation);
  13484. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13485. }
  13486. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13487. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13488. this._currentInstanceLocations.push(offsetLocation);
  13489. this._currentInstanceBuffers.push(instancesBuffer);
  13490. }
  13491. }
  13492. };
  13493. /**
  13494. * Apply all cached states (depth, culling, stencil and alpha)
  13495. */
  13496. Engine.prototype.applyStates = function () {
  13497. this._depthCullingState.apply(this._gl);
  13498. this._stencilState.apply(this._gl);
  13499. this._alphaState.apply(this._gl);
  13500. };
  13501. /**
  13502. * Send a draw order
  13503. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13504. * @param indexStart defines the starting index
  13505. * @param indexCount defines the number of index to draw
  13506. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13507. */
  13508. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13509. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13510. };
  13511. /**
  13512. * Draw a list of points
  13513. * @param verticesStart defines the index of first vertex to draw
  13514. * @param verticesCount defines the count of vertices to draw
  13515. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13516. */
  13517. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13518. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13519. };
  13520. /**
  13521. * Draw a list of unindexed primitives
  13522. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13523. * @param verticesStart defines the index of first vertex to draw
  13524. * @param verticesCount defines the count of vertices to draw
  13525. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13526. */
  13527. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13528. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13529. };
  13530. /**
  13531. * Draw a list of indexed primitives
  13532. * @param fillMode defines the primitive to use
  13533. * @param indexStart defines the starting index
  13534. * @param indexCount defines the number of index to draw
  13535. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13536. */
  13537. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13538. // Apply states
  13539. this.applyStates();
  13540. this._drawCalls.addCount(1, false);
  13541. // Render
  13542. var drawMode = this._drawMode(fillMode);
  13543. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13544. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13545. if (instancesCount) {
  13546. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13547. }
  13548. else {
  13549. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13550. }
  13551. };
  13552. /**
  13553. * Draw a list of unindexed primitives
  13554. * @param fillMode defines the primitive to use
  13555. * @param verticesStart defines the index of first vertex to draw
  13556. * @param verticesCount defines the count of vertices to draw
  13557. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13558. */
  13559. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13560. // Apply states
  13561. this.applyStates();
  13562. this._drawCalls.addCount(1, false);
  13563. var drawMode = this._drawMode(fillMode);
  13564. if (instancesCount) {
  13565. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13566. }
  13567. else {
  13568. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13569. }
  13570. };
  13571. Engine.prototype._drawMode = function (fillMode) {
  13572. switch (fillMode) {
  13573. // Triangle views
  13574. case BABYLON.Material.TriangleFillMode:
  13575. return this._gl.TRIANGLES;
  13576. case BABYLON.Material.PointFillMode:
  13577. return this._gl.POINTS;
  13578. case BABYLON.Material.WireFrameFillMode:
  13579. return this._gl.LINES;
  13580. // Draw modes
  13581. case BABYLON.Material.PointListDrawMode:
  13582. return this._gl.POINTS;
  13583. case BABYLON.Material.LineListDrawMode:
  13584. return this._gl.LINES;
  13585. case BABYLON.Material.LineLoopDrawMode:
  13586. return this._gl.LINE_LOOP;
  13587. case BABYLON.Material.LineStripDrawMode:
  13588. return this._gl.LINE_STRIP;
  13589. case BABYLON.Material.TriangleStripDrawMode:
  13590. return this._gl.TRIANGLE_STRIP;
  13591. case BABYLON.Material.TriangleFanDrawMode:
  13592. return this._gl.TRIANGLE_FAN;
  13593. default:
  13594. return this._gl.TRIANGLES;
  13595. }
  13596. };
  13597. // Shaders
  13598. /** @hidden */
  13599. Engine.prototype._releaseEffect = function (effect) {
  13600. if (this._compiledEffects[effect._key]) {
  13601. delete this._compiledEffects[effect._key];
  13602. this._deleteProgram(effect.getProgram());
  13603. }
  13604. };
  13605. /** @hidden */
  13606. Engine.prototype._deleteProgram = function (program) {
  13607. if (program) {
  13608. program.__SPECTOR_rebuildProgram = null;
  13609. if (program.transformFeedback) {
  13610. this.deleteTransformFeedback(program.transformFeedback);
  13611. program.transformFeedback = null;
  13612. }
  13613. this._gl.deleteProgram(program);
  13614. }
  13615. };
  13616. /**
  13617. * Create a new effect (used to store vertex/fragment shaders)
  13618. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13619. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13620. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13621. * @param samplers defines an array of string used to represent textures
  13622. * @param defines defines the string containing the defines to use to compile the shaders
  13623. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13624. * @param onCompiled defines a function to call when the effect creation is successful
  13625. * @param onError defines a function to call when the effect creation has failed
  13626. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13627. * @returns the new Effect
  13628. */
  13629. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13630. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13631. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13632. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13633. if (this._compiledEffects[name]) {
  13634. var compiledEffect = this._compiledEffects[name];
  13635. if (onCompiled && compiledEffect.isReady()) {
  13636. onCompiled(compiledEffect);
  13637. }
  13638. return compiledEffect;
  13639. }
  13640. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13641. effect._key = name;
  13642. this._compiledEffects[name] = effect;
  13643. return effect;
  13644. };
  13645. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13646. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13647. };
  13648. ;
  13649. Engine.prototype._compileRawShader = function (source, type) {
  13650. var gl = this._gl;
  13651. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13652. gl.shaderSource(shader, source);
  13653. gl.compileShader(shader);
  13654. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13655. var log = gl.getShaderInfoLog(shader);
  13656. if (log) {
  13657. throw new Error(log);
  13658. }
  13659. }
  13660. if (!shader) {
  13661. throw new Error("Something went wrong while compile the shader.");
  13662. }
  13663. return shader;
  13664. };
  13665. ;
  13666. /**
  13667. * Directly creates a webGL program
  13668. * @param vertexCode defines the vertex shader code to use
  13669. * @param fragmentCode defines the fragment shader code to use
  13670. * @param context defines the webGL context to use (if not set, the current one will be used)
  13671. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13672. * @returns the new webGL program
  13673. */
  13674. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13675. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13676. context = context || this._gl;
  13677. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13678. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13679. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13680. };
  13681. /**
  13682. * Creates a webGL program
  13683. * @param vertexCode defines the vertex shader code to use
  13684. * @param fragmentCode defines the fragment shader code to use
  13685. * @param defines defines the string containing the defines to use to compile the shaders
  13686. * @param context defines the webGL context to use (if not set, the current one will be used)
  13687. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13688. * @returns the new webGL program
  13689. */
  13690. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13691. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13692. context = context || this._gl;
  13693. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13694. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13695. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13696. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13697. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13698. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13699. return program;
  13700. };
  13701. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13702. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13703. var shaderProgram = context.createProgram();
  13704. if (!shaderProgram) {
  13705. throw new Error("Unable to create program");
  13706. }
  13707. context.attachShader(shaderProgram, vertexShader);
  13708. context.attachShader(shaderProgram, fragmentShader);
  13709. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13710. var transformFeedback = this.createTransformFeedback();
  13711. this.bindTransformFeedback(transformFeedback);
  13712. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13713. shaderProgram.transformFeedback = transformFeedback;
  13714. }
  13715. context.linkProgram(shaderProgram);
  13716. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13717. this.bindTransformFeedback(null);
  13718. }
  13719. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13720. if (!linked) {
  13721. var error = context.getProgramInfoLog(shaderProgram);
  13722. if (error) {
  13723. throw new Error(error);
  13724. }
  13725. }
  13726. if (this.validateShaderPrograms) {
  13727. context.validateProgram(shaderProgram);
  13728. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13729. if (!validated) {
  13730. var error = context.getProgramInfoLog(shaderProgram);
  13731. if (error) {
  13732. throw new Error(error);
  13733. }
  13734. }
  13735. }
  13736. context.deleteShader(vertexShader);
  13737. context.deleteShader(fragmentShader);
  13738. return shaderProgram;
  13739. };
  13740. /**
  13741. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13742. * @param shaderProgram defines the webGL program to use
  13743. * @param uniformsNames defines the list of uniform names
  13744. * @returns an array of webGL uniform locations
  13745. */
  13746. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13747. var results = new Array();
  13748. for (var index = 0; index < uniformsNames.length; index++) {
  13749. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13750. }
  13751. return results;
  13752. };
  13753. /**
  13754. * Gets the lsit of active attributes for a given webGL program
  13755. * @param shaderProgram defines the webGL program to use
  13756. * @param attributesNames defines the list of attribute names to get
  13757. * @returns an array of indices indicating the offset of each attribute
  13758. */
  13759. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13760. var results = [];
  13761. for (var index = 0; index < attributesNames.length; index++) {
  13762. try {
  13763. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13764. }
  13765. catch (e) {
  13766. results.push(-1);
  13767. }
  13768. }
  13769. return results;
  13770. };
  13771. /**
  13772. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13773. * @param effect defines the effect to activate
  13774. */
  13775. Engine.prototype.enableEffect = function (effect) {
  13776. if (!effect || effect === this._currentEffect) {
  13777. return;
  13778. }
  13779. // Use program
  13780. this.bindSamplers(effect);
  13781. this._currentEffect = effect;
  13782. if (effect.onBind) {
  13783. effect.onBind(effect);
  13784. }
  13785. if (effect._onBindObservable) {
  13786. effect._onBindObservable.notifyObservers(effect);
  13787. }
  13788. };
  13789. /**
  13790. * Set the value of an uniform to an array of int32
  13791. * @param uniform defines the webGL uniform location where to store the value
  13792. * @param array defines the array of int32 to store
  13793. */
  13794. Engine.prototype.setIntArray = function (uniform, array) {
  13795. if (!uniform)
  13796. return;
  13797. this._gl.uniform1iv(uniform, array);
  13798. };
  13799. /**
  13800. * Set the value of an uniform to an array of int32 (stored as vec2)
  13801. * @param uniform defines the webGL uniform location where to store the value
  13802. * @param array defines the array of int32 to store
  13803. */
  13804. Engine.prototype.setIntArray2 = function (uniform, array) {
  13805. if (!uniform || array.length % 2 !== 0)
  13806. return;
  13807. this._gl.uniform2iv(uniform, array);
  13808. };
  13809. /**
  13810. * Set the value of an uniform to an array of int32 (stored as vec3)
  13811. * @param uniform defines the webGL uniform location where to store the value
  13812. * @param array defines the array of int32 to store
  13813. */
  13814. Engine.prototype.setIntArray3 = function (uniform, array) {
  13815. if (!uniform || array.length % 3 !== 0)
  13816. return;
  13817. this._gl.uniform3iv(uniform, array);
  13818. };
  13819. /**
  13820. * Set the value of an uniform to an array of int32 (stored as vec4)
  13821. * @param uniform defines the webGL uniform location where to store the value
  13822. * @param array defines the array of int32 to store
  13823. */
  13824. Engine.prototype.setIntArray4 = function (uniform, array) {
  13825. if (!uniform || array.length % 4 !== 0)
  13826. return;
  13827. this._gl.uniform4iv(uniform, array);
  13828. };
  13829. /**
  13830. * Set the value of an uniform to an array of float32
  13831. * @param uniform defines the webGL uniform location where to store the value
  13832. * @param array defines the array of float32 to store
  13833. */
  13834. Engine.prototype.setFloatArray = function (uniform, array) {
  13835. if (!uniform)
  13836. return;
  13837. this._gl.uniform1fv(uniform, array);
  13838. };
  13839. /**
  13840. * Set the value of an uniform to an array of float32 (stored as vec2)
  13841. * @param uniform defines the webGL uniform location where to store the value
  13842. * @param array defines the array of float32 to store
  13843. */
  13844. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13845. if (!uniform || array.length % 2 !== 0)
  13846. return;
  13847. this._gl.uniform2fv(uniform, array);
  13848. };
  13849. /**
  13850. * Set the value of an uniform to an array of float32 (stored as vec3)
  13851. * @param uniform defines the webGL uniform location where to store the value
  13852. * @param array defines the array of float32 to store
  13853. */
  13854. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13855. if (!uniform || array.length % 3 !== 0)
  13856. return;
  13857. this._gl.uniform3fv(uniform, array);
  13858. };
  13859. /**
  13860. * Set the value of an uniform to an array of float32 (stored as vec4)
  13861. * @param uniform defines the webGL uniform location where to store the value
  13862. * @param array defines the array of float32 to store
  13863. */
  13864. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13865. if (!uniform || array.length % 4 !== 0)
  13866. return;
  13867. this._gl.uniform4fv(uniform, array);
  13868. };
  13869. /**
  13870. * Set the value of an uniform to an array of number
  13871. * @param uniform defines the webGL uniform location where to store the value
  13872. * @param array defines the array of number to store
  13873. */
  13874. Engine.prototype.setArray = function (uniform, array) {
  13875. if (!uniform)
  13876. return;
  13877. this._gl.uniform1fv(uniform, array);
  13878. };
  13879. /**
  13880. * Set the value of an uniform to an array of number (stored as vec2)
  13881. * @param uniform defines the webGL uniform location where to store the value
  13882. * @param array defines the array of number to store
  13883. */
  13884. Engine.prototype.setArray2 = function (uniform, array) {
  13885. if (!uniform || array.length % 2 !== 0)
  13886. return;
  13887. this._gl.uniform2fv(uniform, array);
  13888. };
  13889. /**
  13890. * Set the value of an uniform to an array of number (stored as vec3)
  13891. * @param uniform defines the webGL uniform location where to store the value
  13892. * @param array defines the array of number to store
  13893. */
  13894. Engine.prototype.setArray3 = function (uniform, array) {
  13895. if (!uniform || array.length % 3 !== 0)
  13896. return;
  13897. this._gl.uniform3fv(uniform, array);
  13898. };
  13899. /**
  13900. * Set the value of an uniform to an array of number (stored as vec4)
  13901. * @param uniform defines the webGL uniform location where to store the value
  13902. * @param array defines the array of number to store
  13903. */
  13904. Engine.prototype.setArray4 = function (uniform, array) {
  13905. if (!uniform || array.length % 4 !== 0)
  13906. return;
  13907. this._gl.uniform4fv(uniform, array);
  13908. };
  13909. /**
  13910. * Set the value of an uniform to an array of float32 (stored as matrices)
  13911. * @param uniform defines the webGL uniform location where to store the value
  13912. * @param matrices defines the array of float32 to store
  13913. */
  13914. Engine.prototype.setMatrices = function (uniform, matrices) {
  13915. if (!uniform)
  13916. return;
  13917. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13918. };
  13919. /**
  13920. * Set the value of an uniform to a matrix
  13921. * @param uniform defines the webGL uniform location where to store the value
  13922. * @param matrix defines the matrix to store
  13923. */
  13924. Engine.prototype.setMatrix = function (uniform, matrix) {
  13925. if (!uniform)
  13926. return;
  13927. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13928. };
  13929. /**
  13930. * Set the value of an uniform to a matrix (3x3)
  13931. * @param uniform defines the webGL uniform location where to store the value
  13932. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13933. */
  13934. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13935. if (!uniform)
  13936. return;
  13937. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13938. };
  13939. /**
  13940. * Set the value of an uniform to a matrix (2x2)
  13941. * @param uniform defines the webGL uniform location where to store the value
  13942. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13943. */
  13944. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13945. if (!uniform)
  13946. return;
  13947. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13948. };
  13949. /**
  13950. * Set the value of an uniform to a number (int)
  13951. * @param uniform defines the webGL uniform location where to store the value
  13952. * @param value defines the int number to store
  13953. */
  13954. Engine.prototype.setInt = function (uniform, value) {
  13955. if (!uniform)
  13956. return;
  13957. this._gl.uniform1i(uniform, value);
  13958. };
  13959. /**
  13960. * Set the value of an uniform to a number (float)
  13961. * @param uniform defines the webGL uniform location where to store the value
  13962. * @param value defines the float number to store
  13963. */
  13964. Engine.prototype.setFloat = function (uniform, value) {
  13965. if (!uniform)
  13966. return;
  13967. this._gl.uniform1f(uniform, value);
  13968. };
  13969. /**
  13970. * Set the value of an uniform to a vec2
  13971. * @param uniform defines the webGL uniform location where to store the value
  13972. * @param x defines the 1st component of the value
  13973. * @param y defines the 2nd component of the value
  13974. */
  13975. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13976. if (!uniform)
  13977. return;
  13978. this._gl.uniform2f(uniform, x, y);
  13979. };
  13980. /**
  13981. * Set the value of an uniform to a vec3
  13982. * @param uniform defines the webGL uniform location where to store the value
  13983. * @param x defines the 1st component of the value
  13984. * @param y defines the 2nd component of the value
  13985. * @param z defines the 3rd component of the value
  13986. */
  13987. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13988. if (!uniform)
  13989. return;
  13990. this._gl.uniform3f(uniform, x, y, z);
  13991. };
  13992. /**
  13993. * Set the value of an uniform to a boolean
  13994. * @param uniform defines the webGL uniform location where to store the value
  13995. * @param bool defines the boolean to store
  13996. */
  13997. Engine.prototype.setBool = function (uniform, bool) {
  13998. if (!uniform)
  13999. return;
  14000. this._gl.uniform1i(uniform, bool);
  14001. };
  14002. /**
  14003. * Set the value of an uniform to a vec4
  14004. * @param uniform defines the webGL uniform location where to store the value
  14005. * @param x defines the 1st component of the value
  14006. * @param y defines the 2nd component of the value
  14007. * @param z defines the 3rd component of the value
  14008. * @param w defines the 4th component of the value
  14009. */
  14010. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14011. if (!uniform)
  14012. return;
  14013. this._gl.uniform4f(uniform, x, y, z, w);
  14014. };
  14015. /**
  14016. * Set the value of an uniform to a Color3
  14017. * @param uniform defines the webGL uniform location where to store the value
  14018. * @param color3 defines the color to store
  14019. */
  14020. Engine.prototype.setColor3 = function (uniform, color3) {
  14021. if (!uniform)
  14022. return;
  14023. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14024. };
  14025. /**
  14026. * Set the value of an uniform to a Color3 and an alpha value
  14027. * @param uniform defines the webGL uniform location where to store the value
  14028. * @param color3 defines the color to store
  14029. * @param alpha defines the alpha component to store
  14030. */
  14031. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14032. if (!uniform)
  14033. return;
  14034. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14035. };
  14036. /**
  14037. * Sets a Color4 on a uniform variable
  14038. * @param uniform defines the uniform location
  14039. * @param color4 defines the value to be set
  14040. */
  14041. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14042. if (!uniform)
  14043. return;
  14044. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14045. };
  14046. // States
  14047. /**
  14048. * Set various states to the webGL context
  14049. * @param culling defines backface culling state
  14050. * @param zOffset defines the value to apply to zOffset (0 by default)
  14051. * @param force defines if states must be applied even if cache is up to date
  14052. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14053. */
  14054. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14055. if (zOffset === void 0) { zOffset = 0; }
  14056. if (reverseSide === void 0) { reverseSide = false; }
  14057. // Culling
  14058. if (this._depthCullingState.cull !== culling || force) {
  14059. this._depthCullingState.cull = culling;
  14060. }
  14061. // Cull face
  14062. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14063. if (this._depthCullingState.cullFace !== cullFace || force) {
  14064. this._depthCullingState.cullFace = cullFace;
  14065. }
  14066. // Z offset
  14067. this.setZOffset(zOffset);
  14068. // Front face
  14069. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14070. if (this._depthCullingState.frontFace !== frontFace || force) {
  14071. this._depthCullingState.frontFace = frontFace;
  14072. }
  14073. };
  14074. /**
  14075. * Set the z offset to apply to current rendering
  14076. * @param value defines the offset to apply
  14077. */
  14078. Engine.prototype.setZOffset = function (value) {
  14079. this._depthCullingState.zOffset = value;
  14080. };
  14081. /**
  14082. * Gets the current value of the zOffset
  14083. * @returns the current zOffset state
  14084. */
  14085. Engine.prototype.getZOffset = function () {
  14086. return this._depthCullingState.zOffset;
  14087. };
  14088. /**
  14089. * Enable or disable depth buffering
  14090. * @param enable defines the state to set
  14091. */
  14092. Engine.prototype.setDepthBuffer = function (enable) {
  14093. this._depthCullingState.depthTest = enable;
  14094. };
  14095. /**
  14096. * Gets a boolean indicating if depth writing is enabled
  14097. * @returns the current depth writing state
  14098. */
  14099. Engine.prototype.getDepthWrite = function () {
  14100. return this._depthCullingState.depthMask;
  14101. };
  14102. /**
  14103. * Enable or disable depth writing
  14104. * @param enable defines the state to set
  14105. */
  14106. Engine.prototype.setDepthWrite = function (enable) {
  14107. this._depthCullingState.depthMask = enable;
  14108. };
  14109. /**
  14110. * Enable or disable color writing
  14111. * @param enable defines the state to set
  14112. */
  14113. Engine.prototype.setColorWrite = function (enable) {
  14114. this._gl.colorMask(enable, enable, enable, enable);
  14115. this._colorWrite = enable;
  14116. };
  14117. /**
  14118. * Gets a boolean indicating if color writing is enabled
  14119. * @returns the current color writing state
  14120. */
  14121. Engine.prototype.getColorWrite = function () {
  14122. return this._colorWrite;
  14123. };
  14124. /**
  14125. * Sets alpha constants used by some alpha blending modes
  14126. * @param r defines the red component
  14127. * @param g defines the green component
  14128. * @param b defines the blue component
  14129. * @param a defines the alpha component
  14130. */
  14131. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14132. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14133. };
  14134. /**
  14135. * Sets the current alpha mode
  14136. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14137. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14138. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14139. */
  14140. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14141. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14142. if (this._alphaMode === mode) {
  14143. return;
  14144. }
  14145. switch (mode) {
  14146. case Engine.ALPHA_DISABLE:
  14147. this._alphaState.alphaBlend = false;
  14148. break;
  14149. case Engine.ALPHA_PREMULTIPLIED:
  14150. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14151. this._alphaState.alphaBlend = true;
  14152. break;
  14153. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14154. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14155. this._alphaState.alphaBlend = true;
  14156. break;
  14157. case Engine.ALPHA_COMBINE:
  14158. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14159. this._alphaState.alphaBlend = true;
  14160. break;
  14161. case Engine.ALPHA_ONEONE:
  14162. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14163. this._alphaState.alphaBlend = true;
  14164. break;
  14165. case Engine.ALPHA_ADD:
  14166. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14167. this._alphaState.alphaBlend = true;
  14168. break;
  14169. case Engine.ALPHA_SUBTRACT:
  14170. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14171. this._alphaState.alphaBlend = true;
  14172. break;
  14173. case Engine.ALPHA_MULTIPLY:
  14174. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14175. this._alphaState.alphaBlend = true;
  14176. break;
  14177. case Engine.ALPHA_MAXIMIZED:
  14178. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14179. this._alphaState.alphaBlend = true;
  14180. break;
  14181. case Engine.ALPHA_INTERPOLATE:
  14182. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14183. this._alphaState.alphaBlend = true;
  14184. break;
  14185. case Engine.ALPHA_SCREENMODE:
  14186. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14187. this._alphaState.alphaBlend = true;
  14188. break;
  14189. }
  14190. if (!noDepthWriteChange) {
  14191. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14192. }
  14193. this._alphaMode = mode;
  14194. };
  14195. /**
  14196. * Gets the current alpha mode
  14197. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14198. * @returns the current alpha mode
  14199. */
  14200. Engine.prototype.getAlphaMode = function () {
  14201. return this._alphaMode;
  14202. };
  14203. // Textures
  14204. /**
  14205. * Clears the list of texture accessible through engine.
  14206. * This can help preventing texture load conflict due to name collision.
  14207. */
  14208. Engine.prototype.clearInternalTexturesCache = function () {
  14209. this._internalTexturesCache = [];
  14210. };
  14211. /**
  14212. * Force the entire cache to be cleared
  14213. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14214. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14215. */
  14216. Engine.prototype.wipeCaches = function (bruteForce) {
  14217. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14218. return;
  14219. }
  14220. this._currentEffect = null;
  14221. this._unpackFlipYCached = null;
  14222. this._viewportCached.x = 0;
  14223. this._viewportCached.y = 0;
  14224. this._viewportCached.z = 0;
  14225. this._viewportCached.w = 0;
  14226. if (bruteForce) {
  14227. this.resetTextureCache();
  14228. this._currentProgram = null;
  14229. this._stencilState.reset();
  14230. this._depthCullingState.reset();
  14231. this.setDepthFunctionToLessOrEqual();
  14232. this._alphaState.reset();
  14233. }
  14234. this._resetVertexBufferBinding();
  14235. this._cachedIndexBuffer = null;
  14236. this._cachedEffectForVertexBuffers = null;
  14237. this._unbindVertexArrayObject();
  14238. this.bindIndexBuffer(null);
  14239. };
  14240. /**
  14241. * Set the compressed texture format to use, based on the formats you have, and the formats
  14242. * supported by the hardware / browser.
  14243. *
  14244. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14245. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14246. * to API arguments needed to compressed textures. This puts the burden on the container
  14247. * generator to house the arcane code for determining these for current & future formats.
  14248. *
  14249. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14250. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14251. *
  14252. * Note: The result of this call is not taken into account when a texture is base64.
  14253. *
  14254. * @param formatsAvailable defines the list of those format families you have created
  14255. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14256. *
  14257. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14258. * @returns The extension selected.
  14259. */
  14260. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14261. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14262. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14263. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14264. return this._textureFormatInUse = this._texturesSupported[i];
  14265. }
  14266. }
  14267. }
  14268. // actively set format to nothing, to allow this to be called more than once
  14269. // and possibly fail the 2nd time
  14270. this._textureFormatInUse = null;
  14271. return null;
  14272. };
  14273. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14274. var gl = this._gl;
  14275. var magFilter = gl.NEAREST;
  14276. var minFilter = gl.NEAREST;
  14277. switch (samplingMode) {
  14278. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14279. magFilter = gl.LINEAR;
  14280. if (generateMipMaps) {
  14281. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14282. }
  14283. else {
  14284. minFilter = gl.LINEAR;
  14285. }
  14286. break;
  14287. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14288. magFilter = gl.LINEAR;
  14289. if (generateMipMaps) {
  14290. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14291. }
  14292. else {
  14293. minFilter = gl.LINEAR;
  14294. }
  14295. break;
  14296. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14297. magFilter = gl.NEAREST;
  14298. if (generateMipMaps) {
  14299. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14300. }
  14301. else {
  14302. minFilter = gl.NEAREST;
  14303. }
  14304. break;
  14305. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14306. magFilter = gl.NEAREST;
  14307. if (generateMipMaps) {
  14308. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14309. }
  14310. else {
  14311. minFilter = gl.NEAREST;
  14312. }
  14313. break;
  14314. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14315. magFilter = gl.NEAREST;
  14316. if (generateMipMaps) {
  14317. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14318. }
  14319. else {
  14320. minFilter = gl.LINEAR;
  14321. }
  14322. break;
  14323. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14324. magFilter = gl.NEAREST;
  14325. if (generateMipMaps) {
  14326. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14327. }
  14328. else {
  14329. minFilter = gl.LINEAR;
  14330. }
  14331. break;
  14332. case Engine.TEXTURE_NEAREST_LINEAR:
  14333. magFilter = gl.NEAREST;
  14334. minFilter = gl.LINEAR;
  14335. break;
  14336. case Engine.TEXTURE_NEAREST_NEAREST:
  14337. magFilter = gl.NEAREST;
  14338. minFilter = gl.NEAREST;
  14339. break;
  14340. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14341. magFilter = gl.LINEAR;
  14342. if (generateMipMaps) {
  14343. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14344. }
  14345. else {
  14346. minFilter = gl.NEAREST;
  14347. }
  14348. break;
  14349. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14350. magFilter = gl.LINEAR;
  14351. if (generateMipMaps) {
  14352. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14353. }
  14354. else {
  14355. minFilter = gl.NEAREST;
  14356. }
  14357. break;
  14358. case Engine.TEXTURE_LINEAR_LINEAR:
  14359. magFilter = gl.LINEAR;
  14360. minFilter = gl.LINEAR;
  14361. break;
  14362. case Engine.TEXTURE_LINEAR_NEAREST:
  14363. magFilter = gl.LINEAR;
  14364. minFilter = gl.NEAREST;
  14365. break;
  14366. }
  14367. return {
  14368. min: minFilter,
  14369. mag: magFilter
  14370. };
  14371. };
  14372. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14373. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14374. var img;
  14375. var onload = function () {
  14376. loadedImages[index] = img;
  14377. loadedImages._internalCount++;
  14378. if (scene) {
  14379. scene._removePendingData(img);
  14380. }
  14381. if (loadedImages._internalCount === 6) {
  14382. onfinish(loadedImages);
  14383. }
  14384. };
  14385. var onerror = function (message, exception) {
  14386. if (scene) {
  14387. scene._removePendingData(img);
  14388. }
  14389. if (onErrorCallBack) {
  14390. onErrorCallBack(message, exception);
  14391. }
  14392. };
  14393. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14394. if (scene) {
  14395. scene._addPendingData(img);
  14396. }
  14397. };
  14398. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14399. if (onError === void 0) { onError = null; }
  14400. var loadedImages = [];
  14401. loadedImages._internalCount = 0;
  14402. for (var index = 0; index < 6; index++) {
  14403. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14404. }
  14405. };
  14406. ;
  14407. /** @hidden */
  14408. Engine.prototype._createTexture = function () {
  14409. var texture = this._gl.createTexture();
  14410. if (!texture) {
  14411. throw new Error("Unable to create texture");
  14412. }
  14413. return texture;
  14414. };
  14415. /**
  14416. * Usually called from BABYLON.Texture.ts.
  14417. * Passed information to create a WebGLTexture
  14418. * @param urlArg defines a value which contains one of the following:
  14419. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14420. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14421. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14422. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14423. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14424. * @param scene needed for loading to the correct scene
  14425. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14426. * @param onLoad optional callback to be called upon successful completion
  14427. * @param onError optional callback to be called upon failure
  14428. * @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
  14429. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14430. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14431. * @param forcedExtension defines the extension to use to pick the right loader
  14432. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14433. */
  14434. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14435. var _this = this;
  14436. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14437. if (onLoad === void 0) { onLoad = null; }
  14438. if (onError === void 0) { onError = null; }
  14439. if (buffer === void 0) { buffer = null; }
  14440. if (fallback === void 0) { fallback = null; }
  14441. if (format === void 0) { format = null; }
  14442. if (forcedExtension === void 0) { forcedExtension = null; }
  14443. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14444. var fromData = url.substr(0, 5) === "data:";
  14445. var fromBlob = url.substr(0, 5) === "blob:";
  14446. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14447. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14448. // establish the file extension, if possible
  14449. var lastDot = url.lastIndexOf('.');
  14450. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14451. var loader = null;
  14452. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14453. var availableLoader = _a[_i];
  14454. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14455. loader = availableLoader;
  14456. break;
  14457. }
  14458. }
  14459. if (loader) {
  14460. url = loader.transformUrl(url, this._textureFormatInUse);
  14461. }
  14462. if (scene) {
  14463. scene._addPendingData(texture);
  14464. }
  14465. texture.url = url;
  14466. texture.generateMipMaps = !noMipmap;
  14467. texture.samplingMode = samplingMode;
  14468. texture.invertY = invertY;
  14469. if (!this._doNotHandleContextLost) {
  14470. // Keep a link to the buffer only if we plan to handle context lost
  14471. texture._buffer = buffer;
  14472. }
  14473. var onLoadObserver = null;
  14474. if (onLoad && !fallback) {
  14475. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14476. }
  14477. if (!fallback)
  14478. this._internalTexturesCache.push(texture);
  14479. var onInternalError = function (message, exception) {
  14480. if (scene) {
  14481. scene._removePendingData(texture);
  14482. }
  14483. var customFallback = false;
  14484. if (loader) {
  14485. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14486. if (fallbackUrl) {
  14487. // Add Back
  14488. customFallback = true;
  14489. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14490. }
  14491. }
  14492. if (!customFallback) {
  14493. if (onLoadObserver) {
  14494. texture.onLoadedObservable.remove(onLoadObserver);
  14495. }
  14496. if (BABYLON.Tools.UseFallbackTexture) {
  14497. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14498. }
  14499. }
  14500. if (onError) {
  14501. onError(message || "Unknown error", exception);
  14502. }
  14503. };
  14504. // processing for non-image formats
  14505. if (loader) {
  14506. var callback = function (data) {
  14507. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14508. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14509. done();
  14510. return false;
  14511. }, samplingMode);
  14512. });
  14513. };
  14514. if (!buffer) {
  14515. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14516. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14517. });
  14518. }
  14519. else {
  14520. callback(buffer);
  14521. }
  14522. }
  14523. else {
  14524. var onload = function (img) {
  14525. if (fromBlob && !_this._doNotHandleContextLost) {
  14526. // We need to store the image if we need to rebuild the texture
  14527. // in case of a webgl context lost
  14528. texture._buffer = img;
  14529. }
  14530. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14531. var gl = _this._gl;
  14532. var isPot = (img.width === potWidth && img.height === potHeight);
  14533. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14534. if (isPot) {
  14535. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14536. return false;
  14537. }
  14538. var maxTextureSize = _this._caps.maxTextureSize;
  14539. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14540. _this._prepareWorkingCanvas();
  14541. if (!_this._workingCanvas || !_this._workingContext) {
  14542. return false;
  14543. }
  14544. _this._workingCanvas.width = potWidth;
  14545. _this._workingCanvas.height = potHeight;
  14546. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14547. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14548. texture.width = potWidth;
  14549. texture.height = potHeight;
  14550. return false;
  14551. }
  14552. else {
  14553. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14554. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14555. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14556. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14557. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14558. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14559. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14560. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14561. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14562. _this._releaseTexture(source_1);
  14563. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14564. continuationCallback();
  14565. });
  14566. }
  14567. return true;
  14568. }, samplingMode);
  14569. };
  14570. if (!fromData || isBase64) {
  14571. if (buffer instanceof HTMLImageElement) {
  14572. onload(buffer);
  14573. }
  14574. else {
  14575. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14576. }
  14577. }
  14578. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14579. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14580. }
  14581. else {
  14582. onload(buffer);
  14583. }
  14584. }
  14585. return texture;
  14586. };
  14587. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14588. var _this = this;
  14589. var rtt = this.createRenderTargetTexture({
  14590. width: destination.width,
  14591. height: destination.height,
  14592. }, {
  14593. generateMipMaps: false,
  14594. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14595. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14596. generateDepthBuffer: false,
  14597. generateStencilBuffer: false
  14598. });
  14599. if (!this._rescalePostProcess) {
  14600. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14601. }
  14602. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14603. _this._rescalePostProcess.onApply = function (effect) {
  14604. effect._bindTexture("textureSampler", source);
  14605. };
  14606. var hostingScene = scene;
  14607. if (!hostingScene) {
  14608. hostingScene = _this.scenes[_this.scenes.length - 1];
  14609. }
  14610. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14611. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14612. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14613. _this.unBindFramebuffer(rtt);
  14614. _this._releaseTexture(rtt);
  14615. if (onComplete) {
  14616. onComplete();
  14617. }
  14618. });
  14619. };
  14620. /**
  14621. * Update a raw texture
  14622. * @param texture defines the texture to update
  14623. * @param data defines the data to store in the texture
  14624. * @param format defines the format of the data
  14625. * @param invertY defines if data must be stored with Y axis inverted
  14626. * @param compression defines the compression used (null by default)
  14627. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14628. */
  14629. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14630. if (compression === void 0) { compression = null; }
  14631. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14632. if (!texture) {
  14633. return;
  14634. }
  14635. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14636. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14637. // babylon's internalFormat but gl's texImage2D format
  14638. var internalFormat = this._getInternalFormat(format);
  14639. var textureType = this._getWebGLTextureType(type);
  14640. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14641. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14642. if (!this._doNotHandleContextLost) {
  14643. texture._bufferView = data;
  14644. texture.format = format;
  14645. texture.type = type;
  14646. texture.invertY = invertY;
  14647. texture._compression = compression;
  14648. }
  14649. if (texture.width % 4 !== 0) {
  14650. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14651. }
  14652. if (compression && data) {
  14653. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14654. }
  14655. else {
  14656. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14657. }
  14658. if (texture.generateMipMaps) {
  14659. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14660. }
  14661. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14662. // this.resetTextureCache();
  14663. texture.isReady = true;
  14664. };
  14665. /**
  14666. * Creates a raw texture
  14667. * @param data defines the data to store in the texture
  14668. * @param width defines the width of the texture
  14669. * @param height defines the height of the texture
  14670. * @param format defines the format of the data
  14671. * @param generateMipMaps defines if the engine should generate the mip levels
  14672. * @param invertY defines if data must be stored with Y axis inverted
  14673. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14674. * @param compression defines the compression used (null by default)
  14675. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14676. * @returns the raw texture inside an InternalTexture
  14677. */
  14678. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14679. if (compression === void 0) { compression = null; }
  14680. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14681. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14682. texture.baseWidth = width;
  14683. texture.baseHeight = height;
  14684. texture.width = width;
  14685. texture.height = height;
  14686. texture.format = format;
  14687. texture.generateMipMaps = generateMipMaps;
  14688. texture.samplingMode = samplingMode;
  14689. texture.invertY = invertY;
  14690. texture._compression = compression;
  14691. texture.type = type;
  14692. if (!this._doNotHandleContextLost) {
  14693. texture._bufferView = data;
  14694. }
  14695. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14696. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14697. // Filters
  14698. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14699. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14700. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14701. if (generateMipMaps) {
  14702. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14703. }
  14704. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14705. this._internalTexturesCache.push(texture);
  14706. return texture;
  14707. };
  14708. /** @hidden */
  14709. Engine.prototype._unpackFlipY = function (value) {
  14710. if (this._unpackFlipYCached !== value) {
  14711. this._unpackFlipYCached = value;
  14712. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14713. }
  14714. };
  14715. /** @hidden */
  14716. Engine.prototype._getUnpackAlignement = function () {
  14717. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14718. };
  14719. /**
  14720. * Creates a dynamic texture
  14721. * @param width defines the width of the texture
  14722. * @param height defines the height of the texture
  14723. * @param generateMipMaps defines if the engine should generate the mip levels
  14724. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14725. * @returns the dynamic texture inside an InternalTexture
  14726. */
  14727. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14728. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14729. texture.baseWidth = width;
  14730. texture.baseHeight = height;
  14731. if (generateMipMaps) {
  14732. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14733. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14734. }
  14735. // this.resetTextureCache();
  14736. texture.width = width;
  14737. texture.height = height;
  14738. texture.isReady = false;
  14739. texture.generateMipMaps = generateMipMaps;
  14740. texture.samplingMode = samplingMode;
  14741. this.updateTextureSamplingMode(samplingMode, texture);
  14742. this._internalTexturesCache.push(texture);
  14743. return texture;
  14744. };
  14745. /**
  14746. * Update the sampling mode of a given texture
  14747. * @param samplingMode defines the required sampling mode
  14748. * @param texture defines the texture to update
  14749. */
  14750. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14751. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14752. if (texture.isCube) {
  14753. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14754. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14755. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14756. }
  14757. else if (texture.is3D) {
  14758. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14759. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14760. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14761. }
  14762. else {
  14763. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14764. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14765. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14766. }
  14767. texture.samplingMode = samplingMode;
  14768. };
  14769. /**
  14770. * Update the content of a dynamic texture
  14771. * @param texture defines the texture to update
  14772. * @param canvas defines the canvas containing the source
  14773. * @param invertY defines if data must be stored with Y axis inverted
  14774. * @param premulAlpha defines if alpha is stored as premultiplied
  14775. * @param format defines the format of the data
  14776. */
  14777. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14778. if (premulAlpha === void 0) { premulAlpha = false; }
  14779. if (!texture) {
  14780. return;
  14781. }
  14782. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14783. this._unpackFlipY(invertY);
  14784. if (premulAlpha) {
  14785. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14786. }
  14787. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14788. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14789. if (texture.generateMipMaps) {
  14790. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14791. }
  14792. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14793. if (premulAlpha) {
  14794. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14795. }
  14796. texture.isReady = true;
  14797. };
  14798. /**
  14799. * Update a video texture
  14800. * @param texture defines the texture to update
  14801. * @param video defines the video element to use
  14802. * @param invertY defines if data must be stored with Y axis inverted
  14803. */
  14804. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14805. if (!texture || texture._isDisabled) {
  14806. return;
  14807. }
  14808. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14809. this._unpackFlipY(!invertY); // Video are upside down by default
  14810. try {
  14811. // Testing video texture support
  14812. if (this._videoTextureSupported === undefined) {
  14813. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14814. if (this._gl.getError() !== 0) {
  14815. this._videoTextureSupported = false;
  14816. }
  14817. else {
  14818. this._videoTextureSupported = true;
  14819. }
  14820. }
  14821. // Copy video through the current working canvas if video texture is not supported
  14822. if (!this._videoTextureSupported) {
  14823. if (!texture._workingCanvas) {
  14824. texture._workingCanvas = document.createElement("canvas");
  14825. var context = texture._workingCanvas.getContext("2d");
  14826. if (!context) {
  14827. throw new Error("Unable to get 2d context");
  14828. }
  14829. texture._workingContext = context;
  14830. texture._workingCanvas.width = texture.width;
  14831. texture._workingCanvas.height = texture.height;
  14832. }
  14833. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14834. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14835. }
  14836. else {
  14837. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14838. }
  14839. if (texture.generateMipMaps) {
  14840. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14841. }
  14842. if (!wasPreviouslyBound) {
  14843. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14844. }
  14845. // this.resetTextureCache();
  14846. texture.isReady = true;
  14847. }
  14848. catch (ex) {
  14849. // Something unexpected
  14850. // Let's disable the texture
  14851. texture._isDisabled = true;
  14852. }
  14853. };
  14854. /**
  14855. * Updates a depth texture Comparison Mode and Function.
  14856. * If the comparison Function is equal to 0, the mode will be set to none.
  14857. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14858. * @param texture The texture to set the comparison function for
  14859. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14860. */
  14861. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14862. if (this.webGLVersion === 1) {
  14863. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14864. return;
  14865. }
  14866. var gl = this._gl;
  14867. if (texture.isCube) {
  14868. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14869. if (comparisonFunction === 0) {
  14870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14872. }
  14873. else {
  14874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14876. }
  14877. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14878. }
  14879. else {
  14880. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14881. if (comparisonFunction === 0) {
  14882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14884. }
  14885. else {
  14886. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14887. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14888. }
  14889. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14890. }
  14891. texture._comparisonFunction = comparisonFunction;
  14892. };
  14893. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14894. var width = size.width || size;
  14895. var height = size.height || size;
  14896. internalTexture.baseWidth = width;
  14897. internalTexture.baseHeight = height;
  14898. internalTexture.width = width;
  14899. internalTexture.height = height;
  14900. internalTexture.isReady = true;
  14901. internalTexture.samples = 1;
  14902. internalTexture.generateMipMaps = false;
  14903. internalTexture._generateDepthBuffer = true;
  14904. internalTexture._generateStencilBuffer = generateStencil;
  14905. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14906. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14907. internalTexture._comparisonFunction = comparisonFunction;
  14908. var gl = this._gl;
  14909. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14910. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14911. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14912. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14913. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14914. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14915. if (comparisonFunction === 0) {
  14916. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14917. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14918. }
  14919. else {
  14920. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14921. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14922. }
  14923. };
  14924. /**
  14925. * Creates a depth stencil texture.
  14926. * This is only available in WebGL 2 or with the depth texture extension available.
  14927. * @param size The size of face edge in the texture.
  14928. * @param options The options defining the texture.
  14929. * @returns The texture
  14930. */
  14931. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14932. if (options.isCube) {
  14933. var width = size.width || size;
  14934. return this._createDepthStencilCubeTexture(width, options);
  14935. }
  14936. else {
  14937. return this._createDepthStencilTexture(size, options);
  14938. }
  14939. };
  14940. /**
  14941. * Creates a depth stencil texture.
  14942. * This is only available in WebGL 2 or with the depth texture extension available.
  14943. * @param size The size of face edge in the texture.
  14944. * @param options The options defining the texture.
  14945. * @returns The texture
  14946. */
  14947. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14948. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14949. if (!this._caps.depthTextureExtension) {
  14950. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14951. return internalTexture;
  14952. }
  14953. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14954. var gl = this._gl;
  14955. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14956. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14957. if (this.webGLVersion > 1) {
  14958. if (internalOptions.generateStencil) {
  14959. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14960. }
  14961. else {
  14962. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14963. }
  14964. }
  14965. else {
  14966. if (internalOptions.generateStencil) {
  14967. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14968. }
  14969. else {
  14970. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14971. }
  14972. }
  14973. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14974. return internalTexture;
  14975. };
  14976. /**
  14977. * Creates a depth stencil cube texture.
  14978. * This is only available in WebGL 2.
  14979. * @param size The size of face edge in the cube texture.
  14980. * @param options The options defining the cube texture.
  14981. * @returns The cube texture
  14982. */
  14983. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14984. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14985. internalTexture.isCube = true;
  14986. if (this.webGLVersion === 1) {
  14987. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14988. return internalTexture;
  14989. }
  14990. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14991. var gl = this._gl;
  14992. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14993. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14994. // Create the depth/stencil buffer
  14995. for (var face = 0; face < 6; face++) {
  14996. if (internalOptions.generateStencil) {
  14997. 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);
  14998. }
  14999. else {
  15000. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15001. }
  15002. }
  15003. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15004. return internalTexture;
  15005. };
  15006. /**
  15007. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15008. * @param renderTarget The render target to set the frame buffer for
  15009. */
  15010. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15011. // Create the framebuffer
  15012. var internalTexture = renderTarget.getInternalTexture();
  15013. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15014. return;
  15015. }
  15016. var gl = this._gl;
  15017. var depthStencilTexture = renderTarget.depthStencilTexture;
  15018. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15019. if (depthStencilTexture.isCube) {
  15020. if (depthStencilTexture._generateStencilBuffer) {
  15021. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15022. }
  15023. else {
  15024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15025. }
  15026. }
  15027. else {
  15028. if (depthStencilTexture._generateStencilBuffer) {
  15029. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15030. }
  15031. else {
  15032. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15033. }
  15034. }
  15035. this.bindUnboundFramebuffer(null);
  15036. };
  15037. /**
  15038. * Creates a new render target texture
  15039. * @param size defines the size of the texture
  15040. * @param options defines the options used to create the texture
  15041. * @returns a new render target texture stored in an InternalTexture
  15042. */
  15043. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15044. var fullOptions = new RenderTargetCreationOptions();
  15045. if (options !== undefined && typeof options === "object") {
  15046. fullOptions.generateMipMaps = options.generateMipMaps;
  15047. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15048. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15049. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15050. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15051. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15052. }
  15053. else {
  15054. fullOptions.generateMipMaps = options;
  15055. fullOptions.generateDepthBuffer = true;
  15056. fullOptions.generateStencilBuffer = false;
  15057. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15058. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15059. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15060. }
  15061. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15062. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15063. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15064. }
  15065. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15066. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15067. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15068. }
  15069. var gl = this._gl;
  15070. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15071. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15072. var width = size.width || size;
  15073. var height = size.height || size;
  15074. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15075. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15076. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15077. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15078. }
  15079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15081. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15082. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15083. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15084. // Create the framebuffer
  15085. var currentFrameBuffer = this._currentFramebuffer;
  15086. var framebuffer = gl.createFramebuffer();
  15087. this.bindUnboundFramebuffer(framebuffer);
  15088. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15089. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15090. if (fullOptions.generateMipMaps) {
  15091. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15092. }
  15093. // Unbind
  15094. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15095. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15096. this.bindUnboundFramebuffer(currentFrameBuffer);
  15097. texture._framebuffer = framebuffer;
  15098. texture.baseWidth = width;
  15099. texture.baseHeight = height;
  15100. texture.width = width;
  15101. texture.height = height;
  15102. texture.isReady = true;
  15103. texture.samples = 1;
  15104. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15105. texture.samplingMode = fullOptions.samplingMode;
  15106. texture.type = fullOptions.type;
  15107. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15108. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15109. // this.resetTextureCache();
  15110. this._internalTexturesCache.push(texture);
  15111. return texture;
  15112. };
  15113. /**
  15114. * Create a multi render target texture
  15115. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15116. * @param size defines the size of the texture
  15117. * @param options defines the creation options
  15118. * @returns the cube texture as an InternalTexture
  15119. */
  15120. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15121. var generateMipMaps = false;
  15122. var generateDepthBuffer = true;
  15123. var generateStencilBuffer = false;
  15124. var generateDepthTexture = false;
  15125. var textureCount = 1;
  15126. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15127. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15128. var types = new Array();
  15129. var samplingModes = new Array();
  15130. if (options !== undefined) {
  15131. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15132. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15133. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15134. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15135. textureCount = options.textureCount || 1;
  15136. if (options.types) {
  15137. types = options.types;
  15138. }
  15139. if (options.samplingModes) {
  15140. samplingModes = options.samplingModes;
  15141. }
  15142. }
  15143. var gl = this._gl;
  15144. // Create the framebuffer
  15145. var framebuffer = gl.createFramebuffer();
  15146. this.bindUnboundFramebuffer(framebuffer);
  15147. var width = size.width || size;
  15148. var height = size.height || size;
  15149. var textures = [];
  15150. var attachments = [];
  15151. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15152. for (var i = 0; i < textureCount; i++) {
  15153. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15154. var type = types[i] || defaultType;
  15155. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15156. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15157. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15158. }
  15159. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15160. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15161. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15162. }
  15163. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15164. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15165. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15166. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15167. }
  15168. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15169. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15170. textures.push(texture);
  15171. attachments.push(attachment);
  15172. gl.activeTexture(gl["TEXTURE" + i]);
  15173. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15178. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15179. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15180. if (generateMipMaps) {
  15181. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15182. }
  15183. // Unbind
  15184. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15185. texture._framebuffer = framebuffer;
  15186. texture._depthStencilBuffer = depthStencilBuffer;
  15187. texture.baseWidth = width;
  15188. texture.baseHeight = height;
  15189. texture.width = width;
  15190. texture.height = height;
  15191. texture.isReady = true;
  15192. texture.samples = 1;
  15193. texture.generateMipMaps = generateMipMaps;
  15194. texture.samplingMode = samplingMode;
  15195. texture.type = type;
  15196. texture._generateDepthBuffer = generateDepthBuffer;
  15197. texture._generateStencilBuffer = generateStencilBuffer;
  15198. texture._attachments = attachments;
  15199. this._internalTexturesCache.push(texture);
  15200. }
  15201. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15202. // Depth texture
  15203. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15204. gl.activeTexture(gl.TEXTURE0);
  15205. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15206. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15207. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15210. 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);
  15211. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15212. depthTexture._framebuffer = framebuffer;
  15213. depthTexture.baseWidth = width;
  15214. depthTexture.baseHeight = height;
  15215. depthTexture.width = width;
  15216. depthTexture.height = height;
  15217. depthTexture.isReady = true;
  15218. depthTexture.samples = 1;
  15219. depthTexture.generateMipMaps = generateMipMaps;
  15220. depthTexture.samplingMode = gl.NEAREST;
  15221. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15222. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15223. textures.push(depthTexture);
  15224. this._internalTexturesCache.push(depthTexture);
  15225. }
  15226. gl.drawBuffers(attachments);
  15227. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15228. this.bindUnboundFramebuffer(null);
  15229. this.resetTextureCache();
  15230. return textures;
  15231. };
  15232. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15233. if (samples === void 0) { samples = 1; }
  15234. var depthStencilBuffer = null;
  15235. var gl = this._gl;
  15236. // Create the depth/stencil buffer
  15237. if (generateStencilBuffer) {
  15238. depthStencilBuffer = gl.createRenderbuffer();
  15239. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15240. if (samples > 1) {
  15241. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15242. }
  15243. else {
  15244. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15245. }
  15246. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15247. }
  15248. else if (generateDepthBuffer) {
  15249. depthStencilBuffer = gl.createRenderbuffer();
  15250. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15251. if (samples > 1) {
  15252. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15253. }
  15254. else {
  15255. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15256. }
  15257. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15258. }
  15259. return depthStencilBuffer;
  15260. };
  15261. /**
  15262. * Updates the sample count of a render target texture
  15263. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15264. * @param texture defines the texture to update
  15265. * @param samples defines the sample count to set
  15266. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15267. */
  15268. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15269. if (this.webGLVersion < 2 || !texture) {
  15270. return 1;
  15271. }
  15272. if (texture.samples === samples) {
  15273. return samples;
  15274. }
  15275. var gl = this._gl;
  15276. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15277. // Dispose previous render buffers
  15278. if (texture._depthStencilBuffer) {
  15279. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15280. texture._depthStencilBuffer = null;
  15281. }
  15282. if (texture._MSAAFramebuffer) {
  15283. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15284. texture._MSAAFramebuffer = null;
  15285. }
  15286. if (texture._MSAARenderBuffer) {
  15287. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15288. texture._MSAARenderBuffer = null;
  15289. }
  15290. if (samples > 1) {
  15291. var framebuffer = gl.createFramebuffer();
  15292. if (!framebuffer) {
  15293. throw new Error("Unable to create multi sampled framebuffer");
  15294. }
  15295. texture._MSAAFramebuffer = framebuffer;
  15296. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15297. var colorRenderbuffer = gl.createRenderbuffer();
  15298. if (!colorRenderbuffer) {
  15299. throw new Error("Unable to create multi sampled framebuffer");
  15300. }
  15301. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15302. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15303. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15304. texture._MSAARenderBuffer = colorRenderbuffer;
  15305. }
  15306. else {
  15307. this.bindUnboundFramebuffer(texture._framebuffer);
  15308. }
  15309. texture.samples = samples;
  15310. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15311. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15312. this.bindUnboundFramebuffer(null);
  15313. return samples;
  15314. };
  15315. /**
  15316. * Update the sample count for a given multiple render target texture
  15317. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15318. * @param textures defines the textures to update
  15319. * @param samples defines the sample count to set
  15320. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15321. */
  15322. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15323. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15324. return 1;
  15325. }
  15326. if (textures[0].samples === samples) {
  15327. return samples;
  15328. }
  15329. var gl = this._gl;
  15330. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15331. // Dispose previous render buffers
  15332. if (textures[0]._depthStencilBuffer) {
  15333. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15334. textures[0]._depthStencilBuffer = null;
  15335. }
  15336. if (textures[0]._MSAAFramebuffer) {
  15337. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15338. textures[0]._MSAAFramebuffer = null;
  15339. }
  15340. for (var i = 0; i < textures.length; i++) {
  15341. if (textures[i]._MSAARenderBuffer) {
  15342. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15343. textures[i]._MSAARenderBuffer = null;
  15344. }
  15345. }
  15346. if (samples > 1) {
  15347. var framebuffer = gl.createFramebuffer();
  15348. if (!framebuffer) {
  15349. throw new Error("Unable to create multi sampled framebuffer");
  15350. }
  15351. this.bindUnboundFramebuffer(framebuffer);
  15352. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15353. var attachments = [];
  15354. for (var i = 0; i < textures.length; i++) {
  15355. var texture = textures[i];
  15356. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15357. var colorRenderbuffer = gl.createRenderbuffer();
  15358. if (!colorRenderbuffer) {
  15359. throw new Error("Unable to create multi sampled framebuffer");
  15360. }
  15361. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15362. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15363. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15364. texture._MSAAFramebuffer = framebuffer;
  15365. texture._MSAARenderBuffer = colorRenderbuffer;
  15366. texture.samples = samples;
  15367. texture._depthStencilBuffer = depthStencilBuffer;
  15368. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15369. attachments.push(attachment);
  15370. }
  15371. gl.drawBuffers(attachments);
  15372. }
  15373. else {
  15374. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15375. }
  15376. this.bindUnboundFramebuffer(null);
  15377. return samples;
  15378. };
  15379. /** @hidden */
  15380. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15381. if (faceIndex === void 0) { faceIndex = 0; }
  15382. if (lod === void 0) { lod = 0; }
  15383. var gl = this._gl;
  15384. var target = gl.TEXTURE_2D;
  15385. if (texture.isCube) {
  15386. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15387. }
  15388. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15389. };
  15390. /** @hidden */
  15391. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15392. if (faceIndex === void 0) { faceIndex = 0; }
  15393. if (lod === void 0) { lod = 0; }
  15394. var gl = this._gl;
  15395. var textureType = this._getWebGLTextureType(texture.type);
  15396. var format = this._getInternalFormat(texture.format);
  15397. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15398. this._unpackFlipY(texture.invertY);
  15399. var target = gl.TEXTURE_2D;
  15400. if (texture.isCube) {
  15401. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15402. }
  15403. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15404. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15405. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15406. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15407. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15408. };
  15409. /** @hidden */
  15410. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15411. if (faceIndex === void 0) { faceIndex = 0; }
  15412. if (lod === void 0) { lod = 0; }
  15413. var gl = this._gl;
  15414. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15415. this._bindTextureDirectly(bindTarget, texture, true);
  15416. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15417. this._bindTextureDirectly(bindTarget, null, true);
  15418. };
  15419. /** @hidden */
  15420. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15421. if (faceIndex === void 0) { faceIndex = 0; }
  15422. if (lod === void 0) { lod = 0; }
  15423. var gl = this._gl;
  15424. var textureType = this._getWebGLTextureType(texture.type);
  15425. var format = this._getInternalFormat(texture.format);
  15426. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15427. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15428. this._bindTextureDirectly(bindTarget, texture, true);
  15429. this._unpackFlipY(texture.invertY);
  15430. var target = gl.TEXTURE_2D;
  15431. if (texture.isCube) {
  15432. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15433. }
  15434. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15435. this._bindTextureDirectly(bindTarget, null, true);
  15436. };
  15437. /**
  15438. * Creates a new render target cube texture
  15439. * @param size defines the size of the texture
  15440. * @param options defines the options used to create the texture
  15441. * @returns a new render target cube texture stored in an InternalTexture
  15442. */
  15443. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15444. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15445. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15446. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15447. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15448. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15449. }
  15450. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15451. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15452. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15453. }
  15454. var gl = this._gl;
  15455. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15456. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15457. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15458. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15459. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15460. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15461. }
  15462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15466. for (var face = 0; face < 6; face++) {
  15467. 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);
  15468. }
  15469. // Create the framebuffer
  15470. var framebuffer = gl.createFramebuffer();
  15471. this.bindUnboundFramebuffer(framebuffer);
  15472. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15473. // MipMaps
  15474. if (fullOptions.generateMipMaps) {
  15475. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15476. }
  15477. // Unbind
  15478. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15479. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15480. this.bindUnboundFramebuffer(null);
  15481. texture._framebuffer = framebuffer;
  15482. texture.width = size;
  15483. texture.height = size;
  15484. texture.isReady = true;
  15485. texture.isCube = true;
  15486. texture.samples = 1;
  15487. texture.generateMipMaps = fullOptions.generateMipMaps;
  15488. texture.samplingMode = fullOptions.samplingMode;
  15489. texture.type = fullOptions.type;
  15490. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15491. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15492. this._internalTexturesCache.push(texture);
  15493. return texture;
  15494. };
  15495. /**
  15496. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15497. * @param rootUrl defines the url where the file to load is located
  15498. * @param scene defines the current scene
  15499. * @param lodScale defines scale to apply to the mip map selection
  15500. * @param lodOffset defines offset to apply to the mip map selection
  15501. * @param onLoad defines an optional callback raised when the texture is loaded
  15502. * @param onError defines an optional callback raised if there is an issue to load the texture
  15503. * @param format defines the format of the data
  15504. * @param forcedExtension defines the extension to use to pick the right loader
  15505. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15506. * @returns the cube texture as an InternalTexture
  15507. */
  15508. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15509. var _this = this;
  15510. if (onLoad === void 0) { onLoad = null; }
  15511. if (onError === void 0) { onError = null; }
  15512. if (forcedExtension === void 0) { forcedExtension = null; }
  15513. if (createPolynomials === void 0) { createPolynomials = true; }
  15514. var callback = function (loadData) {
  15515. if (!loadData) {
  15516. if (onLoad) {
  15517. onLoad(null);
  15518. }
  15519. return;
  15520. }
  15521. var texture = loadData.texture;
  15522. if (!createPolynomials) {
  15523. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15524. }
  15525. else if (loadData.info.sphericalPolynomial) {
  15526. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15527. }
  15528. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15529. if (_this._caps.textureLOD) {
  15530. // Do not add extra process if texture lod is supported.
  15531. if (onLoad) {
  15532. onLoad(texture);
  15533. }
  15534. return;
  15535. }
  15536. var mipSlices = 3;
  15537. var gl = _this._gl;
  15538. var width = loadData.width;
  15539. if (!width) {
  15540. return;
  15541. }
  15542. var textures = [];
  15543. for (var i = 0; i < mipSlices; i++) {
  15544. //compute LOD from even spacing in smoothness (matching shader calculation)
  15545. var smoothness = i / (mipSlices - 1);
  15546. var roughness = 1 - smoothness;
  15547. var minLODIndex = lodOffset; // roughness = 0
  15548. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15549. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15550. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15551. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15552. glTextureFromLod.type = texture.type;
  15553. glTextureFromLod.format = texture.format;
  15554. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15555. glTextureFromLod.height = glTextureFromLod.width;
  15556. glTextureFromLod.isCube = true;
  15557. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15560. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15561. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15562. if (loadData.isDDS) {
  15563. var info = loadData.info;
  15564. var data = loadData.data;
  15565. _this._unpackFlipY(info.isCompressed);
  15566. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15567. }
  15568. else {
  15569. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15570. }
  15571. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15572. // Wrap in a base texture for easy binding.
  15573. var lodTexture = new BABYLON.BaseTexture(scene);
  15574. lodTexture.isCube = true;
  15575. lodTexture._texture = glTextureFromLod;
  15576. glTextureFromLod.isReady = true;
  15577. textures.push(lodTexture);
  15578. }
  15579. texture._lodTextureHigh = textures[2];
  15580. texture._lodTextureMid = textures[1];
  15581. texture._lodTextureLow = textures[0];
  15582. if (onLoad) {
  15583. onLoad(texture);
  15584. }
  15585. };
  15586. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15587. };
  15588. /**
  15589. * Creates a cube texture
  15590. * @param rootUrl defines the url where the files to load is located
  15591. * @param scene defines the current scene
  15592. * @param files defines the list of files to load (1 per face)
  15593. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15594. * @param onLoad defines an optional callback raised when the texture is loaded
  15595. * @param onError defines an optional callback raised if there is an issue to load the texture
  15596. * @param format defines the format of the data
  15597. * @param forcedExtension defines the extension to use to pick the right loader
  15598. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15599. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15600. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15601. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15602. * @returns the cube texture as an InternalTexture
  15603. */
  15604. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15605. var _this = this;
  15606. if (onLoad === void 0) { onLoad = null; }
  15607. if (onError === void 0) { onError = null; }
  15608. if (forcedExtension === void 0) { forcedExtension = null; }
  15609. if (createPolynomials === void 0) { createPolynomials = false; }
  15610. if (lodScale === void 0) { lodScale = 0; }
  15611. if (lodOffset === void 0) { lodOffset = 0; }
  15612. if (fallback === void 0) { fallback = null; }
  15613. var gl = this._gl;
  15614. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15615. texture.isCube = true;
  15616. texture.url = rootUrl;
  15617. texture.generateMipMaps = !noMipmap;
  15618. texture._lodGenerationScale = lodScale;
  15619. texture._lodGenerationOffset = lodOffset;
  15620. if (!this._doNotHandleContextLost) {
  15621. texture._extension = forcedExtension;
  15622. texture._files = files;
  15623. }
  15624. var lastDot = rootUrl.lastIndexOf('.');
  15625. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15626. var loader = null;
  15627. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15628. var availableLoader = _a[_i];
  15629. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15630. loader = availableLoader;
  15631. break;
  15632. }
  15633. }
  15634. var onInternalError = function (request, exception) {
  15635. if (loader) {
  15636. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15637. if (fallbackUrl) {
  15638. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15639. }
  15640. }
  15641. if (onError && request) {
  15642. onError(request.status + " " + request.statusText, exception);
  15643. }
  15644. };
  15645. if (loader) {
  15646. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15647. var onloaddata = function (data) {
  15648. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15649. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15650. };
  15651. if (files && files.length === 6) {
  15652. if (loader.supportCascades) {
  15653. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15654. }
  15655. else if (onError) {
  15656. onError("Textures type does not support cascades.");
  15657. }
  15658. }
  15659. else {
  15660. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15661. }
  15662. }
  15663. else {
  15664. if (!files) {
  15665. throw new Error("Cannot load cubemap because files were not defined");
  15666. }
  15667. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15668. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15669. var height = width;
  15670. _this._prepareWorkingCanvas();
  15671. if (!_this._workingCanvas || !_this._workingContext) {
  15672. return;
  15673. }
  15674. _this._workingCanvas.width = width;
  15675. _this._workingCanvas.height = height;
  15676. var faces = [
  15677. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15678. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15679. ];
  15680. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15681. _this._unpackFlipY(false);
  15682. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15683. for (var index = 0; index < faces.length; index++) {
  15684. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15685. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15686. }
  15687. if (!noMipmap) {
  15688. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15689. }
  15690. _this._setCubeMapTextureParams(!noMipmap);
  15691. texture.width = width;
  15692. texture.height = height;
  15693. texture.isReady = true;
  15694. if (format) {
  15695. texture.format = format;
  15696. }
  15697. texture.onLoadedObservable.notifyObservers(texture);
  15698. texture.onLoadedObservable.clear();
  15699. if (onLoad) {
  15700. onLoad();
  15701. }
  15702. }, files, onError);
  15703. }
  15704. this._internalTexturesCache.push(texture);
  15705. return texture;
  15706. };
  15707. /**
  15708. * @hidden
  15709. */
  15710. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15711. var gl = this._gl;
  15712. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15713. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15714. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15716. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15717. // this.resetTextureCache();
  15718. };
  15719. /**
  15720. * Update a raw cube texture
  15721. * @param texture defines the texture to udpdate
  15722. * @param data defines the data to store
  15723. * @param format defines the data format
  15724. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15725. * @param invertY defines if data must be stored with Y axis inverted
  15726. * @param compression defines the compression used (null by default)
  15727. * @param level defines which level of the texture to update
  15728. */
  15729. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15730. if (compression === void 0) { compression = null; }
  15731. if (level === void 0) { level = 0; }
  15732. texture._bufferViewArray = data;
  15733. texture.format = format;
  15734. texture.type = type;
  15735. texture.invertY = invertY;
  15736. texture._compression = compression;
  15737. var gl = this._gl;
  15738. var textureType = this._getWebGLTextureType(type);
  15739. var internalFormat = this._getInternalFormat(format);
  15740. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15741. var needConversion = false;
  15742. if (internalFormat === gl.RGB) {
  15743. internalFormat = gl.RGBA;
  15744. needConversion = true;
  15745. }
  15746. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15747. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15748. if (texture.width % 4 !== 0) {
  15749. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15750. }
  15751. // Data are known to be in +X +Y +Z -X -Y -Z
  15752. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15753. var faceData = data[faceIndex];
  15754. if (compression) {
  15755. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15756. }
  15757. else {
  15758. if (needConversion) {
  15759. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15760. }
  15761. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15762. }
  15763. }
  15764. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15765. if (isPot && texture.generateMipMaps && level === 0) {
  15766. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15767. }
  15768. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15769. // this.resetTextureCache();
  15770. texture.isReady = true;
  15771. };
  15772. /**
  15773. * Creates a new raw cube texture
  15774. * @param data defines the array of data to use to create each face
  15775. * @param size defines the size of the textures
  15776. * @param format defines the format of the data
  15777. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15778. * @param generateMipMaps defines if the engine should generate the mip levels
  15779. * @param invertY defines if data must be stored with Y axis inverted
  15780. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15781. * @param compression defines the compression used (null by default)
  15782. * @returns the cube texture as an InternalTexture
  15783. */
  15784. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15785. if (compression === void 0) { compression = null; }
  15786. var gl = this._gl;
  15787. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15788. texture.isCube = true;
  15789. texture.format = format;
  15790. texture.type = type;
  15791. if (!this._doNotHandleContextLost) {
  15792. texture._bufferViewArray = data;
  15793. }
  15794. var textureType = this._getWebGLTextureType(type);
  15795. var internalFormat = this._getInternalFormat(format);
  15796. if (internalFormat === gl.RGB) {
  15797. internalFormat = gl.RGBA;
  15798. }
  15799. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15800. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15801. generateMipMaps = false;
  15802. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15803. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15804. }
  15805. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15806. generateMipMaps = false;
  15807. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15808. BABYLON.Tools.Warn("Half 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 === gl.FLOAT && !this._caps.textureFloatRender) {
  15811. generateMipMaps = false;
  15812. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15813. }
  15814. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15815. generateMipMaps = false;
  15816. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15817. }
  15818. var width = size;
  15819. var height = width;
  15820. texture.width = width;
  15821. texture.height = height;
  15822. // Double check on POT to generate Mips.
  15823. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15824. if (!isPot) {
  15825. generateMipMaps = false;
  15826. }
  15827. // Upload data if needed. The texture won't be ready until then.
  15828. if (data) {
  15829. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15830. }
  15831. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15832. // Filters
  15833. if (data && generateMipMaps) {
  15834. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15835. }
  15836. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15838. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15840. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15841. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15842. texture.generateMipMaps = generateMipMaps;
  15843. return texture;
  15844. };
  15845. /**
  15846. * Creates a new raw cube texture from a specified url
  15847. * @param url defines the url where the data is located
  15848. * @param scene defines the current scene
  15849. * @param size defines the size of the textures
  15850. * @param format defines the format of the data
  15851. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15852. * @param noMipmap defines if the engine should avoid generating the mip levels
  15853. * @param callback defines a callback used to extract texture data from loaded data
  15854. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15855. * @param onLoad defines a callback called when texture is loaded
  15856. * @param onError defines a callback called if there is an error
  15857. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15858. * @param invertY defines if data must be stored with Y axis inverted
  15859. * @returns the cube texture as an InternalTexture
  15860. */
  15861. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15862. var _this = this;
  15863. if (onLoad === void 0) { onLoad = null; }
  15864. if (onError === void 0) { onError = null; }
  15865. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15866. if (invertY === void 0) { invertY = false; }
  15867. var gl = this._gl;
  15868. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15869. scene._addPendingData(texture);
  15870. texture.url = url;
  15871. this._internalTexturesCache.push(texture);
  15872. var onerror = function (request, exception) {
  15873. scene._removePendingData(texture);
  15874. if (onError && request) {
  15875. onError(request.status + " " + request.statusText, exception);
  15876. }
  15877. };
  15878. var internalCallback = function (data) {
  15879. var width = texture.width;
  15880. var faceDataArrays = callback(data);
  15881. if (!faceDataArrays) {
  15882. return;
  15883. }
  15884. if (mipmapGenerator) {
  15885. var textureType = _this._getWebGLTextureType(type);
  15886. var internalFormat = _this._getInternalFormat(format);
  15887. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15888. var needConversion = false;
  15889. if (internalFormat === gl.RGB) {
  15890. internalFormat = gl.RGBA;
  15891. needConversion = true;
  15892. }
  15893. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15894. _this._unpackFlipY(false);
  15895. var mipData = mipmapGenerator(faceDataArrays);
  15896. for (var level = 0; level < mipData.length; level++) {
  15897. var mipSize = width >> level;
  15898. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15899. var mipFaceData = mipData[level][faceIndex];
  15900. if (needConversion) {
  15901. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15902. }
  15903. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15904. }
  15905. }
  15906. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15907. }
  15908. else {
  15909. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15910. }
  15911. texture.isReady = true;
  15912. // this.resetTextureCache();
  15913. scene._removePendingData(texture);
  15914. if (onLoad) {
  15915. onLoad();
  15916. }
  15917. };
  15918. this._loadFile(url, function (data) {
  15919. internalCallback(data);
  15920. }, undefined, scene.database, true, onerror);
  15921. return texture;
  15922. };
  15923. ;
  15924. /**
  15925. * Update a raw 3D texture
  15926. * @param texture defines the texture to update
  15927. * @param data defines the data to store
  15928. * @param format defines the data format
  15929. * @param invertY defines if data must be stored with Y axis inverted
  15930. * @param compression defines the used compression (can be null)
  15931. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15932. */
  15933. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15934. if (compression === void 0) { compression = null; }
  15935. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15936. var internalType = this._getWebGLTextureType(textureType);
  15937. var internalFormat = this._getInternalFormat(format);
  15938. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15939. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15940. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15941. if (!this._doNotHandleContextLost) {
  15942. texture._bufferView = data;
  15943. texture.format = format;
  15944. texture.invertY = invertY;
  15945. texture._compression = compression;
  15946. }
  15947. if (texture.width % 4 !== 0) {
  15948. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15949. }
  15950. if (compression && data) {
  15951. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15952. }
  15953. else {
  15954. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15955. }
  15956. if (texture.generateMipMaps) {
  15957. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15958. }
  15959. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15960. // this.resetTextureCache();
  15961. texture.isReady = true;
  15962. };
  15963. /**
  15964. * Creates a new raw 3D texture
  15965. * @param data defines the data used to create the texture
  15966. * @param width defines the width of the texture
  15967. * @param height defines the height of the texture
  15968. * @param depth defines the depth of the texture
  15969. * @param format defines the format of the texture
  15970. * @param generateMipMaps defines if the engine must generate mip levels
  15971. * @param invertY defines if data must be stored with Y axis inverted
  15972. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15973. * @param compression defines the compressed used (can be null)
  15974. * @param textureType defines the compressed used (can be null)
  15975. * @returns a new raw 3D texture (stored in an InternalTexture)
  15976. */
  15977. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15978. if (compression === void 0) { compression = null; }
  15979. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15980. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15981. texture.baseWidth = width;
  15982. texture.baseHeight = height;
  15983. texture.baseDepth = depth;
  15984. texture.width = width;
  15985. texture.height = height;
  15986. texture.depth = depth;
  15987. texture.format = format;
  15988. texture.type = textureType;
  15989. texture.generateMipMaps = generateMipMaps;
  15990. texture.samplingMode = samplingMode;
  15991. texture.is3D = true;
  15992. if (!this._doNotHandleContextLost) {
  15993. texture._bufferView = data;
  15994. }
  15995. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15996. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15997. // Filters
  15998. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15999. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16000. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16001. if (generateMipMaps) {
  16002. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16003. }
  16004. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16005. this._internalTexturesCache.push(texture);
  16006. return texture;
  16007. };
  16008. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16009. var gl = this._gl;
  16010. if (!gl) {
  16011. return;
  16012. }
  16013. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16016. if (!noMipmap && !isCompressed) {
  16017. gl.generateMipmap(gl.TEXTURE_2D);
  16018. }
  16019. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16020. // this.resetTextureCache();
  16021. if (scene) {
  16022. scene._removePendingData(texture);
  16023. }
  16024. texture.onLoadedObservable.notifyObservers(texture);
  16025. texture.onLoadedObservable.clear();
  16026. };
  16027. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16028. var _this = this;
  16029. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16030. var maxTextureSize = this.getCaps().maxTextureSize;
  16031. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16032. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16033. var gl = this._gl;
  16034. if (!gl) {
  16035. return;
  16036. }
  16037. if (!texture._webGLTexture) {
  16038. // this.resetTextureCache();
  16039. if (scene) {
  16040. scene._removePendingData(texture);
  16041. }
  16042. return;
  16043. }
  16044. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16045. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16046. texture.baseWidth = width;
  16047. texture.baseHeight = height;
  16048. texture.width = potWidth;
  16049. texture.height = potHeight;
  16050. texture.isReady = true;
  16051. if (processFunction(potWidth, potHeight, function () {
  16052. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16053. })) {
  16054. // Returning as texture needs extra async steps
  16055. return;
  16056. }
  16057. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16058. };
  16059. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16060. // Create new RGBA data container.
  16061. var rgbaData;
  16062. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16063. rgbaData = new Float32Array(width * height * 4);
  16064. }
  16065. else {
  16066. rgbaData = new Uint32Array(width * height * 4);
  16067. }
  16068. // Convert each pixel.
  16069. for (var x = 0; x < width; x++) {
  16070. for (var y = 0; y < height; y++) {
  16071. var index = (y * width + x) * 3;
  16072. var newIndex = (y * width + x) * 4;
  16073. // Map Old Value to new value.
  16074. rgbaData[newIndex + 0] = rgbData[index + 0];
  16075. rgbaData[newIndex + 1] = rgbData[index + 1];
  16076. rgbaData[newIndex + 2] = rgbData[index + 2];
  16077. // Add fully opaque alpha channel.
  16078. rgbaData[newIndex + 3] = 1;
  16079. }
  16080. }
  16081. return rgbaData;
  16082. };
  16083. /** @hidden */
  16084. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16085. var gl = this._gl;
  16086. if (texture._framebuffer) {
  16087. gl.deleteFramebuffer(texture._framebuffer);
  16088. texture._framebuffer = null;
  16089. }
  16090. if (texture._depthStencilBuffer) {
  16091. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16092. texture._depthStencilBuffer = null;
  16093. }
  16094. if (texture._MSAAFramebuffer) {
  16095. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16096. texture._MSAAFramebuffer = null;
  16097. }
  16098. if (texture._MSAARenderBuffer) {
  16099. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16100. texture._MSAARenderBuffer = null;
  16101. }
  16102. };
  16103. /** @hidden */
  16104. Engine.prototype._releaseTexture = function (texture) {
  16105. var gl = this._gl;
  16106. this._releaseFramebufferObjects(texture);
  16107. gl.deleteTexture(texture._webGLTexture);
  16108. // Unbind channels
  16109. this.unbindAllTextures();
  16110. var index = this._internalTexturesCache.indexOf(texture);
  16111. if (index !== -1) {
  16112. this._internalTexturesCache.splice(index, 1);
  16113. }
  16114. // Integrated fixed lod samplers.
  16115. if (texture._lodTextureHigh) {
  16116. texture._lodTextureHigh.dispose();
  16117. }
  16118. if (texture._lodTextureMid) {
  16119. texture._lodTextureMid.dispose();
  16120. }
  16121. if (texture._lodTextureLow) {
  16122. texture._lodTextureLow.dispose();
  16123. }
  16124. // Set output texture of post process to null if the texture has been released/disposed
  16125. this.scenes.forEach(function (scene) {
  16126. scene.postProcesses.forEach(function (postProcess) {
  16127. if (postProcess._outputTexture == texture) {
  16128. postProcess._outputTexture = null;
  16129. }
  16130. });
  16131. scene.cameras.forEach(function (camera) {
  16132. camera._postProcesses.forEach(function (postProcess) {
  16133. if (postProcess) {
  16134. if (postProcess._outputTexture == texture) {
  16135. postProcess._outputTexture = null;
  16136. }
  16137. }
  16138. });
  16139. });
  16140. });
  16141. };
  16142. Engine.prototype.setProgram = function (program) {
  16143. if (this._currentProgram !== program) {
  16144. this._gl.useProgram(program);
  16145. this._currentProgram = program;
  16146. }
  16147. };
  16148. /**
  16149. * Binds an effect to the webGL context
  16150. * @param effect defines the effect to bind
  16151. */
  16152. Engine.prototype.bindSamplers = function (effect) {
  16153. this.setProgram(effect.getProgram());
  16154. var samplers = effect.getSamplers();
  16155. for (var index = 0; index < samplers.length; index++) {
  16156. var uniform = effect.getUniform(samplers[index]);
  16157. if (uniform) {
  16158. this._boundUniforms[index] = uniform;
  16159. }
  16160. }
  16161. this._currentEffect = null;
  16162. };
  16163. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16164. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16165. return;
  16166. }
  16167. // Remove
  16168. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16169. // Bind last to it
  16170. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16171. // Bind to dummy
  16172. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16173. };
  16174. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16175. if (!internalTexture) {
  16176. return -1;
  16177. }
  16178. internalTexture._initialSlot = channel;
  16179. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16180. if (channel !== internalTexture._designatedSlot) {
  16181. this._textureCollisions.addCount(1, false);
  16182. }
  16183. }
  16184. else {
  16185. if (channel !== internalTexture._designatedSlot) {
  16186. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16187. return internalTexture._designatedSlot;
  16188. }
  16189. else {
  16190. // No slot for this texture, let's pick a new one (if we find a free slot)
  16191. if (this._nextFreeTextureSlots.length) {
  16192. return this._nextFreeTextureSlots[0];
  16193. }
  16194. // We need to recycle the oldest bound texture, sorry.
  16195. this._textureCollisions.addCount(1, false);
  16196. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16197. }
  16198. }
  16199. }
  16200. return channel;
  16201. };
  16202. Engine.prototype._linkTrackers = function (previous, next) {
  16203. previous.next = next;
  16204. next.previous = previous;
  16205. };
  16206. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16207. var currentSlot = internalTexture._designatedSlot;
  16208. if (currentSlot === -1) {
  16209. return -1;
  16210. }
  16211. internalTexture._designatedSlot = -1;
  16212. if (this.disableTextureBindingOptimization) {
  16213. return -1;
  16214. }
  16215. // Remove from bound list
  16216. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16217. // Free the slot
  16218. this._boundTexturesCache[currentSlot] = null;
  16219. this._nextFreeTextureSlots.push(currentSlot);
  16220. return currentSlot;
  16221. };
  16222. Engine.prototype._activateCurrentTexture = function () {
  16223. if (this._currentTextureChannel !== this._activeChannel) {
  16224. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16225. this._currentTextureChannel = this._activeChannel;
  16226. }
  16227. };
  16228. /** @hidden */
  16229. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16230. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16231. if (force === void 0) { force = false; }
  16232. var wasPreviouslyBound = false;
  16233. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16234. this._activeChannel = texture._designatedSlot;
  16235. }
  16236. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16237. var isTextureForRendering = texture && texture._initialSlot > -1;
  16238. if (currentTextureBound !== texture || force) {
  16239. if (currentTextureBound) {
  16240. this._removeDesignatedSlot(currentTextureBound);
  16241. }
  16242. this._activateCurrentTexture();
  16243. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16244. this._boundTexturesCache[this._activeChannel] = texture;
  16245. if (texture) {
  16246. if (!this.disableTextureBindingOptimization) {
  16247. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16248. if (slotIndex > -1) {
  16249. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16250. }
  16251. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16252. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16253. }
  16254. texture._designatedSlot = this._activeChannel;
  16255. }
  16256. }
  16257. else if (forTextureDataUpdate) {
  16258. wasPreviouslyBound = true;
  16259. this._activateCurrentTexture();
  16260. }
  16261. if (isTextureForRendering && !forTextureDataUpdate) {
  16262. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16263. }
  16264. return wasPreviouslyBound;
  16265. };
  16266. /** @hidden */
  16267. Engine.prototype._bindTexture = function (channel, texture) {
  16268. if (channel < 0) {
  16269. return;
  16270. }
  16271. if (texture) {
  16272. channel = this._getCorrectTextureChannel(channel, texture);
  16273. }
  16274. this._activeChannel = channel;
  16275. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16276. };
  16277. /**
  16278. * Sets a texture to the webGL context from a postprocess
  16279. * @param channel defines the channel to use
  16280. * @param postProcess defines the source postprocess
  16281. */
  16282. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16283. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16284. };
  16285. /**
  16286. * Binds the output of the passed in post process to the texture channel specified
  16287. * @param channel The channel the texture should be bound to
  16288. * @param postProcess The post process which's output should be bound
  16289. */
  16290. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16291. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16292. };
  16293. /**
  16294. * Unbind all textures from the webGL context
  16295. */
  16296. Engine.prototype.unbindAllTextures = function () {
  16297. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16298. this._activeChannel = channel;
  16299. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16300. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16301. if (this.webGLVersion > 1) {
  16302. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16303. }
  16304. }
  16305. };
  16306. /**
  16307. * Sets a texture to the according uniform.
  16308. * @param channel The texture channel
  16309. * @param uniform The uniform to set
  16310. * @param texture The texture to apply
  16311. */
  16312. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16313. if (channel < 0) {
  16314. return;
  16315. }
  16316. if (uniform) {
  16317. this._boundUniforms[channel] = uniform;
  16318. }
  16319. this._setTexture(channel, texture);
  16320. };
  16321. /**
  16322. * Sets a depth stencil texture from a render target to the according uniform.
  16323. * @param channel The texture channel
  16324. * @param uniform The uniform to set
  16325. * @param texture The render target texture containing the depth stencil texture to apply
  16326. */
  16327. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16328. if (channel < 0) {
  16329. return;
  16330. }
  16331. if (uniform) {
  16332. this._boundUniforms[channel] = uniform;
  16333. }
  16334. if (!texture || !texture.depthStencilTexture) {
  16335. this._setTexture(channel, null);
  16336. }
  16337. else {
  16338. this._setTexture(channel, texture, false, true);
  16339. }
  16340. };
  16341. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16342. var uniform = this._boundUniforms[sourceSlot];
  16343. if (uniform._currentState === destination) {
  16344. return;
  16345. }
  16346. this._gl.uniform1i(uniform, destination);
  16347. uniform._currentState = destination;
  16348. };
  16349. Engine.prototype._getTextureWrapMode = function (mode) {
  16350. switch (mode) {
  16351. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16352. return this._gl.REPEAT;
  16353. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16354. return this._gl.CLAMP_TO_EDGE;
  16355. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16356. return this._gl.MIRRORED_REPEAT;
  16357. }
  16358. return this._gl.REPEAT;
  16359. };
  16360. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16361. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16362. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16363. // Not ready?
  16364. if (!texture) {
  16365. if (this._boundTexturesCache[channel] != null) {
  16366. this._activeChannel = channel;
  16367. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16368. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16369. if (this.webGLVersion > 1) {
  16370. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16371. }
  16372. }
  16373. return false;
  16374. }
  16375. // Video
  16376. if (texture.video) {
  16377. this._activeChannel = channel;
  16378. texture.update();
  16379. }
  16380. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16381. texture.delayLoad();
  16382. return false;
  16383. }
  16384. var internalTexture;
  16385. if (depthStencilTexture) {
  16386. internalTexture = texture.depthStencilTexture;
  16387. }
  16388. else if (texture.isReady()) {
  16389. internalTexture = texture.getInternalTexture();
  16390. }
  16391. else if (texture.isCube) {
  16392. internalTexture = this.emptyCubeTexture;
  16393. }
  16394. else if (texture.is3D) {
  16395. internalTexture = this.emptyTexture3D;
  16396. }
  16397. else {
  16398. internalTexture = this.emptyTexture;
  16399. }
  16400. if (!isPartOfTextureArray) {
  16401. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16402. }
  16403. var needToBind = true;
  16404. if (this._boundTexturesCache[channel] === internalTexture) {
  16405. this._moveBoundTextureOnTop(internalTexture);
  16406. if (!isPartOfTextureArray) {
  16407. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16408. }
  16409. needToBind = false;
  16410. }
  16411. this._activeChannel = channel;
  16412. if (internalTexture && internalTexture.is3D) {
  16413. if (needToBind) {
  16414. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16415. }
  16416. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16417. internalTexture._cachedWrapU = texture.wrapU;
  16418. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16419. }
  16420. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16421. internalTexture._cachedWrapV = texture.wrapV;
  16422. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16423. }
  16424. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16425. internalTexture._cachedWrapR = texture.wrapR;
  16426. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16427. }
  16428. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16429. }
  16430. else if (internalTexture && internalTexture.isCube) {
  16431. if (needToBind) {
  16432. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16433. }
  16434. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16435. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16436. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16437. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16438. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16439. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16440. }
  16441. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16442. }
  16443. else {
  16444. if (needToBind) {
  16445. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16446. }
  16447. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16448. internalTexture._cachedWrapU = texture.wrapU;
  16449. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16450. }
  16451. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16452. internalTexture._cachedWrapV = texture.wrapV;
  16453. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16454. }
  16455. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16456. }
  16457. return true;
  16458. };
  16459. /**
  16460. * Sets an array of texture to the webGL context
  16461. * @param channel defines the channel where the texture array must be set
  16462. * @param uniform defines the associated uniform location
  16463. * @param textures defines the array of textures to bind
  16464. */
  16465. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16466. if (channel < 0 || !uniform) {
  16467. return;
  16468. }
  16469. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16470. this._textureUnits = new Int32Array(textures.length);
  16471. }
  16472. for (var i = 0; i < textures.length; i++) {
  16473. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16474. }
  16475. this._gl.uniform1iv(uniform, this._textureUnits);
  16476. for (var index = 0; index < textures.length; index++) {
  16477. this._setTexture(this._textureUnits[index], textures[index], true);
  16478. }
  16479. };
  16480. /** @hidden */
  16481. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16482. var internalTexture = texture.getInternalTexture();
  16483. if (!internalTexture) {
  16484. return;
  16485. }
  16486. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16487. var value = texture.anisotropicFilteringLevel;
  16488. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16489. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16490. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16491. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16492. }
  16493. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16494. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16495. internalTexture._cachedAnisotropicFilteringLevel = value;
  16496. }
  16497. };
  16498. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16499. this._bindTextureDirectly(target, texture, true, true);
  16500. this._gl.texParameterf(target, parameter, value);
  16501. };
  16502. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16503. if (texture) {
  16504. this._bindTextureDirectly(target, texture, true, true);
  16505. }
  16506. this._gl.texParameteri(target, parameter, value);
  16507. };
  16508. /**
  16509. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16510. * @param x defines the x coordinate of the rectangle where pixels must be read
  16511. * @param y defines the y coordinate of the rectangle where pixels must be read
  16512. * @param width defines the width of the rectangle where pixels must be read
  16513. * @param height defines the height of the rectangle where pixels must be read
  16514. * @returns a Uint8Array containing RGBA colors
  16515. */
  16516. Engine.prototype.readPixels = function (x, y, width, height) {
  16517. var data = new Uint8Array(height * width * 4);
  16518. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16519. return data;
  16520. };
  16521. /**
  16522. * Add an externaly attached data from its key.
  16523. * This method call will fail and return false, if such key already exists.
  16524. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16525. * @param key the unique key that identifies the data
  16526. * @param data the data object to associate to the key for this Engine instance
  16527. * @return true if no such key were already present and the data was added successfully, false otherwise
  16528. */
  16529. Engine.prototype.addExternalData = function (key, data) {
  16530. if (!this._externalData) {
  16531. this._externalData = new BABYLON.StringDictionary();
  16532. }
  16533. return this._externalData.add(key, data);
  16534. };
  16535. /**
  16536. * Get an externaly attached data from its key
  16537. * @param key the unique key that identifies the data
  16538. * @return the associated data, if present (can be null), or undefined if not present
  16539. */
  16540. Engine.prototype.getExternalData = function (key) {
  16541. if (!this._externalData) {
  16542. this._externalData = new BABYLON.StringDictionary();
  16543. }
  16544. return this._externalData.get(key);
  16545. };
  16546. /**
  16547. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16548. * @param key the unique key that identifies the data
  16549. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16550. * @return the associated data, can be null if the factory returned null.
  16551. */
  16552. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16553. if (!this._externalData) {
  16554. this._externalData = new BABYLON.StringDictionary();
  16555. }
  16556. return this._externalData.getOrAddWithFactory(key, factory);
  16557. };
  16558. /**
  16559. * Remove an externaly attached data from the Engine instance
  16560. * @param key the unique key that identifies the data
  16561. * @return true if the data was successfully removed, false if it doesn't exist
  16562. */
  16563. Engine.prototype.removeExternalData = function (key) {
  16564. if (!this._externalData) {
  16565. this._externalData = new BABYLON.StringDictionary();
  16566. }
  16567. return this._externalData.remove(key);
  16568. };
  16569. /**
  16570. * Unbind all vertex attributes from the webGL context
  16571. */
  16572. Engine.prototype.unbindAllAttributes = function () {
  16573. if (this._mustWipeVertexAttributes) {
  16574. this._mustWipeVertexAttributes = false;
  16575. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16576. this._gl.disableVertexAttribArray(i);
  16577. this._vertexAttribArraysEnabled[i] = false;
  16578. this._currentBufferPointers[i].active = false;
  16579. }
  16580. return;
  16581. }
  16582. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16583. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16584. continue;
  16585. }
  16586. this._gl.disableVertexAttribArray(i);
  16587. this._vertexAttribArraysEnabled[i] = false;
  16588. this._currentBufferPointers[i].active = false;
  16589. }
  16590. };
  16591. /**
  16592. * 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
  16593. */
  16594. Engine.prototype.releaseEffects = function () {
  16595. for (var name in this._compiledEffects) {
  16596. this._deleteProgram(this._compiledEffects[name]._program);
  16597. }
  16598. this._compiledEffects = {};
  16599. };
  16600. /**
  16601. * Dispose and release all associated resources
  16602. */
  16603. Engine.prototype.dispose = function () {
  16604. this.hideLoadingUI();
  16605. this.stopRenderLoop();
  16606. // Release postProcesses
  16607. while (this.postProcesses.length) {
  16608. this.postProcesses[0].dispose();
  16609. }
  16610. // Empty texture
  16611. if (this._emptyTexture) {
  16612. this._releaseTexture(this._emptyTexture);
  16613. this._emptyTexture = null;
  16614. }
  16615. if (this._emptyCubeTexture) {
  16616. this._releaseTexture(this._emptyCubeTexture);
  16617. this._emptyCubeTexture = null;
  16618. }
  16619. // Rescale PP
  16620. if (this._rescalePostProcess) {
  16621. this._rescalePostProcess.dispose();
  16622. }
  16623. // Release scenes
  16624. while (this.scenes.length) {
  16625. this.scenes[0].dispose();
  16626. }
  16627. // Release audio engine
  16628. if (Engine.audioEngine) {
  16629. Engine.audioEngine.dispose();
  16630. }
  16631. // Release effects
  16632. this.releaseEffects();
  16633. // Unbind
  16634. this.unbindAllAttributes();
  16635. this._boundUniforms = [];
  16636. if (this._dummyFramebuffer) {
  16637. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16638. }
  16639. //WebVR
  16640. this.disableVR();
  16641. // Events
  16642. if (BABYLON.Tools.IsWindowObjectExist()) {
  16643. window.removeEventListener("blur", this._onBlur);
  16644. window.removeEventListener("focus", this._onFocus);
  16645. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16646. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16647. if (this._renderingCanvas) {
  16648. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16649. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16650. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16651. if (!this._doNotHandleContextLost) {
  16652. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16653. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16654. }
  16655. }
  16656. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16657. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16658. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16659. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16660. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16661. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16662. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16663. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16664. if (this._onVrDisplayConnect) {
  16665. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16666. if (this._onVrDisplayDisconnect) {
  16667. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16668. }
  16669. if (this._onVrDisplayPresentChange) {
  16670. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16671. }
  16672. this._onVrDisplayConnect = null;
  16673. this._onVrDisplayDisconnect = null;
  16674. }
  16675. }
  16676. // Remove from Instances
  16677. var index = Engine.Instances.indexOf(this);
  16678. if (index >= 0) {
  16679. Engine.Instances.splice(index, 1);
  16680. }
  16681. this._workingCanvas = null;
  16682. this._workingContext = null;
  16683. this._currentBufferPointers = [];
  16684. this._renderingCanvas = null;
  16685. this._currentProgram = null;
  16686. this._bindedRenderFunction = null;
  16687. this.onResizeObservable.clear();
  16688. this.onCanvasBlurObservable.clear();
  16689. this.onCanvasFocusObservable.clear();
  16690. this.onCanvasPointerOutObservable.clear();
  16691. this.onBeginFrameObservable.clear();
  16692. this.onEndFrameObservable.clear();
  16693. BABYLON.Effect.ResetCache();
  16694. // Abort active requests
  16695. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16696. var request = _a[_i];
  16697. request.abort();
  16698. }
  16699. };
  16700. // Loading screen
  16701. /**
  16702. * Display the loading screen
  16703. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16704. */
  16705. Engine.prototype.displayLoadingUI = function () {
  16706. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16707. return;
  16708. }
  16709. var loadingScreen = this.loadingScreen;
  16710. if (loadingScreen) {
  16711. loadingScreen.displayLoadingUI();
  16712. }
  16713. };
  16714. /**
  16715. * Hide the loading screen
  16716. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16717. */
  16718. Engine.prototype.hideLoadingUI = function () {
  16719. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16720. return;
  16721. }
  16722. var loadingScreen = this.loadingScreen;
  16723. if (loadingScreen) {
  16724. loadingScreen.hideLoadingUI();
  16725. }
  16726. };
  16727. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16728. /**
  16729. * Gets the current loading screen object
  16730. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16731. */
  16732. get: function () {
  16733. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16734. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16735. return this._loadingScreen;
  16736. },
  16737. /**
  16738. * Sets the current loading screen object
  16739. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16740. */
  16741. set: function (loadingScreen) {
  16742. this._loadingScreen = loadingScreen;
  16743. },
  16744. enumerable: true,
  16745. configurable: true
  16746. });
  16747. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16748. /**
  16749. * Sets the current loading screen text
  16750. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16751. */
  16752. set: function (text) {
  16753. this.loadingScreen.loadingUIText = text;
  16754. },
  16755. enumerable: true,
  16756. configurable: true
  16757. });
  16758. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16759. /**
  16760. * Sets the current loading screen background color
  16761. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16762. */
  16763. set: function (color) {
  16764. this.loadingScreen.loadingUIBackgroundColor = color;
  16765. },
  16766. enumerable: true,
  16767. configurable: true
  16768. });
  16769. /**
  16770. * Attach a new callback raised when context lost event is fired
  16771. * @param callback defines the callback to call
  16772. */
  16773. Engine.prototype.attachContextLostEvent = function (callback) {
  16774. if (this._renderingCanvas) {
  16775. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16776. }
  16777. };
  16778. /**
  16779. * Attach a new callback raised when context restored event is fired
  16780. * @param callback defines the callback to call
  16781. */
  16782. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16783. if (this._renderingCanvas) {
  16784. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16785. }
  16786. };
  16787. /**
  16788. * Gets the source code of the vertex shader associated with a specific webGL program
  16789. * @param program defines the program to use
  16790. * @returns a string containing the source code of the vertex shader associated with the program
  16791. */
  16792. Engine.prototype.getVertexShaderSource = function (program) {
  16793. var shaders = this._gl.getAttachedShaders(program);
  16794. if (!shaders) {
  16795. return null;
  16796. }
  16797. return this._gl.getShaderSource(shaders[0]);
  16798. };
  16799. /**
  16800. * Gets the source code of the fragment shader associated with a specific webGL program
  16801. * @param program defines the program to use
  16802. * @returns a string containing the source code of the fragment shader associated with the program
  16803. */
  16804. Engine.prototype.getFragmentShaderSource = function (program) {
  16805. var shaders = this._gl.getAttachedShaders(program);
  16806. if (!shaders) {
  16807. return null;
  16808. }
  16809. return this._gl.getShaderSource(shaders[1]);
  16810. };
  16811. /**
  16812. * Get the current error code of the webGL context
  16813. * @returns the error code
  16814. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16815. */
  16816. Engine.prototype.getError = function () {
  16817. return this._gl.getError();
  16818. };
  16819. // FPS
  16820. /**
  16821. * Gets the current framerate
  16822. * @returns a number representing the framerate
  16823. */
  16824. Engine.prototype.getFps = function () {
  16825. return this._fps;
  16826. };
  16827. /**
  16828. * Gets the time spent between current and previous frame
  16829. * @returns a number representing the delta time in ms
  16830. */
  16831. Engine.prototype.getDeltaTime = function () {
  16832. return this._deltaTime;
  16833. };
  16834. Engine.prototype._measureFps = function () {
  16835. this._performanceMonitor.sampleFrame();
  16836. this._fps = this._performanceMonitor.averageFPS;
  16837. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16838. };
  16839. /** @hidden */
  16840. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16841. if (faceIndex === void 0) { faceIndex = -1; }
  16842. if (level === void 0) { level = 0; }
  16843. var gl = this._gl;
  16844. if (!this._dummyFramebuffer) {
  16845. var dummy = gl.createFramebuffer();
  16846. if (!dummy) {
  16847. throw new Error("Unable to create dummy framebuffer");
  16848. }
  16849. this._dummyFramebuffer = dummy;
  16850. }
  16851. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16852. if (faceIndex > -1) {
  16853. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16854. }
  16855. else {
  16856. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16857. }
  16858. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16859. var buffer;
  16860. switch (readType) {
  16861. case gl.UNSIGNED_BYTE:
  16862. buffer = new Uint8Array(4 * width * height);
  16863. readType = gl.UNSIGNED_BYTE;
  16864. break;
  16865. default:
  16866. buffer = new Float32Array(4 * width * height);
  16867. readType = gl.FLOAT;
  16868. break;
  16869. }
  16870. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16871. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16872. return buffer;
  16873. };
  16874. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16875. if (this._webGLVersion > 1) {
  16876. return this._caps.colorBufferFloat;
  16877. }
  16878. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16879. };
  16880. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16881. if (this._webGLVersion > 1) {
  16882. return this._caps.colorBufferFloat;
  16883. }
  16884. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16885. };
  16886. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16887. Engine.prototype._canRenderToFramebuffer = function (type) {
  16888. var gl = this._gl;
  16889. //clear existing errors
  16890. while (gl.getError() !== gl.NO_ERROR) { }
  16891. var successful = true;
  16892. var texture = gl.createTexture();
  16893. gl.bindTexture(gl.TEXTURE_2D, texture);
  16894. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16897. var fb = gl.createFramebuffer();
  16898. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16899. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16900. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16901. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16902. successful = successful && (gl.getError() === gl.NO_ERROR);
  16903. //try render by clearing frame buffer's color buffer
  16904. if (successful) {
  16905. gl.clear(gl.COLOR_BUFFER_BIT);
  16906. successful = successful && (gl.getError() === gl.NO_ERROR);
  16907. }
  16908. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16909. if (successful) {
  16910. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16911. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16912. var readFormat = gl.RGBA;
  16913. var readType = gl.UNSIGNED_BYTE;
  16914. var buffer = new Uint8Array(4);
  16915. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16916. successful = successful && (gl.getError() === gl.NO_ERROR);
  16917. }
  16918. //clean up
  16919. gl.deleteTexture(texture);
  16920. gl.deleteFramebuffer(fb);
  16921. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16922. //clear accumulated errors
  16923. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16924. return successful;
  16925. };
  16926. /** @hidden */
  16927. Engine.prototype._getWebGLTextureType = function (type) {
  16928. if (type === Engine.TEXTURETYPE_FLOAT) {
  16929. return this._gl.FLOAT;
  16930. }
  16931. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16932. // Add Half Float Constant.
  16933. return this._gl.HALF_FLOAT_OES;
  16934. }
  16935. return this._gl.UNSIGNED_BYTE;
  16936. };
  16937. ;
  16938. Engine.prototype._getInternalFormat = function (format) {
  16939. var internalFormat = this._gl.RGBA;
  16940. switch (format) {
  16941. case Engine.TEXTUREFORMAT_ALPHA:
  16942. internalFormat = this._gl.ALPHA;
  16943. break;
  16944. case Engine.TEXTUREFORMAT_LUMINANCE:
  16945. internalFormat = this._gl.LUMINANCE;
  16946. break;
  16947. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16948. internalFormat = this._gl.LUMINANCE_ALPHA;
  16949. break;
  16950. case Engine.TEXTUREFORMAT_RGB:
  16951. internalFormat = this._gl.RGB;
  16952. break;
  16953. case Engine.TEXTUREFORMAT_RGBA:
  16954. internalFormat = this._gl.RGBA;
  16955. break;
  16956. case Engine.TEXTUREFORMAT_R:
  16957. internalFormat = this._gl.RED;
  16958. break;
  16959. case Engine.TEXTUREFORMAT_RG:
  16960. internalFormat = this._gl.RG;
  16961. break;
  16962. }
  16963. return internalFormat;
  16964. };
  16965. /** @hidden */
  16966. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16967. if (this._webGLVersion === 1) {
  16968. if (format !== undefined) {
  16969. switch (format) {
  16970. case Engine.TEXTUREFORMAT_LUMINANCE:
  16971. return this._gl.LUMINANCE;
  16972. case Engine.TEXTUREFORMAT_ALPHA:
  16973. return this._gl.ALPHA;
  16974. }
  16975. }
  16976. return this._gl.RGBA;
  16977. }
  16978. if (type === Engine.TEXTURETYPE_FLOAT) {
  16979. if (format !== undefined) {
  16980. switch (format) {
  16981. case Engine.TEXTUREFORMAT_R:
  16982. return this._gl.R32F;
  16983. case Engine.TEXTUREFORMAT_RG:
  16984. return this._gl.RG32F;
  16985. case Engine.TEXTUREFORMAT_RGB:
  16986. return this._gl.RGB32F;
  16987. }
  16988. }
  16989. return this._gl.RGBA32F;
  16990. }
  16991. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16992. if (format) {
  16993. switch (format) {
  16994. case Engine.TEXTUREFORMAT_R:
  16995. return this._gl.R16F;
  16996. case Engine.TEXTUREFORMAT_RG:
  16997. return this._gl.RG16F;
  16998. case Engine.TEXTUREFORMAT_RGB:
  16999. return this._gl.RGB16F;
  17000. }
  17001. }
  17002. return this._gl.RGBA16F;
  17003. }
  17004. if (format !== undefined) {
  17005. switch (format) {
  17006. case Engine.TEXTUREFORMAT_LUMINANCE:
  17007. return this._gl.LUMINANCE;
  17008. case Engine.TEXTUREFORMAT_RGB:
  17009. return this._gl.RGB;
  17010. case Engine.TEXTUREFORMAT_R:
  17011. return this._gl.R8;
  17012. case Engine.TEXTUREFORMAT_RG:
  17013. return this._gl.RG8;
  17014. case Engine.TEXTUREFORMAT_ALPHA:
  17015. return this._gl.ALPHA;
  17016. }
  17017. }
  17018. return this._gl.RGBA;
  17019. };
  17020. ;
  17021. /** @hidden */
  17022. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17023. if (type === Engine.TEXTURETYPE_FLOAT) {
  17024. return this._gl.RGBA32F;
  17025. }
  17026. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17027. return this._gl.RGBA16F;
  17028. }
  17029. return this._gl.RGBA8;
  17030. };
  17031. ;
  17032. /** @hidden */
  17033. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17034. var _this = this;
  17035. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17036. this._activeRequests.push(request);
  17037. request.onCompleteObservable.add(function (request) {
  17038. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17039. });
  17040. return request;
  17041. };
  17042. /** @hidden */
  17043. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17044. var _this = this;
  17045. return new Promise(function (resolve, reject) {
  17046. _this._loadFile(url, function (data) {
  17047. resolve(data);
  17048. }, undefined, database, useArrayBuffer, function (request, exception) {
  17049. reject(exception);
  17050. });
  17051. });
  17052. };
  17053. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17054. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17055. var onload = function (data) {
  17056. loadedFiles[index] = data;
  17057. loadedFiles._internalCount++;
  17058. if (loadedFiles._internalCount === 6) {
  17059. onfinish(loadedFiles);
  17060. }
  17061. };
  17062. var onerror = function (request, exception) {
  17063. if (onErrorCallBack && request) {
  17064. onErrorCallBack(request.status + " " + request.statusText, exception);
  17065. }
  17066. };
  17067. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17068. };
  17069. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17070. if (onError === void 0) { onError = null; }
  17071. var loadedFiles = [];
  17072. loadedFiles._internalCount = 0;
  17073. for (var index = 0; index < 6; index++) {
  17074. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17075. }
  17076. };
  17077. // Statics
  17078. /**
  17079. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17080. * @returns true if the engine can be created
  17081. * @ignorenaming
  17082. */
  17083. Engine.isSupported = function () {
  17084. try {
  17085. var tempcanvas = document.createElement("canvas");
  17086. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17087. return gl != null && !!window.WebGLRenderingContext;
  17088. }
  17089. catch (e) {
  17090. return false;
  17091. }
  17092. };
  17093. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17094. Engine.ExceptionList = [
  17095. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17096. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17097. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17098. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17099. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17100. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17101. ];
  17102. /** Gets the list of created engines */
  17103. Engine.Instances = new Array();
  17104. /**
  17105. * Hidden
  17106. */
  17107. Engine._TextureLoaders = [];
  17108. // Const statics
  17109. /** Defines that alpha blending is disabled */
  17110. Engine.ALPHA_DISABLE = 0;
  17111. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17112. Engine.ALPHA_ADD = 1;
  17113. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17114. Engine.ALPHA_COMBINE = 2;
  17115. /** Defines that alpha blending to DEST - SRC * DEST */
  17116. Engine.ALPHA_SUBTRACT = 3;
  17117. /** Defines that alpha blending to SRC * DEST */
  17118. Engine.ALPHA_MULTIPLY = 4;
  17119. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17120. Engine.ALPHA_MAXIMIZED = 5;
  17121. /** Defines that alpha blending to SRC + DEST */
  17122. Engine.ALPHA_ONEONE = 6;
  17123. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17124. Engine.ALPHA_PREMULTIPLIED = 7;
  17125. /**
  17126. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17127. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17128. */
  17129. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17130. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17131. Engine.ALPHA_INTERPOLATE = 9;
  17132. /**
  17133. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17134. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17135. */
  17136. Engine.ALPHA_SCREENMODE = 10;
  17137. /** Defines that the ressource is not delayed*/
  17138. Engine.DELAYLOADSTATE_NONE = 0;
  17139. /** Defines that the ressource was successfully delay loaded */
  17140. Engine.DELAYLOADSTATE_LOADED = 1;
  17141. /** Defines that the ressource is currently delay loading */
  17142. Engine.DELAYLOADSTATE_LOADING = 2;
  17143. /** Defines that the ressource is delayed and has not started loading */
  17144. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17145. // Depht or Stencil test Constants.
  17146. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17147. Engine.NEVER = 0x0200;
  17148. /** 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 */
  17149. Engine.ALWAYS = 0x0207;
  17150. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17151. Engine.LESS = 0x0201;
  17152. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17153. Engine.EQUAL = 0x0202;
  17154. /** 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 */
  17155. Engine.LEQUAL = 0x0203;
  17156. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17157. Engine.GREATER = 0x0204;
  17158. /** 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 */
  17159. Engine.GEQUAL = 0x0206;
  17160. /** 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 */
  17161. Engine.NOTEQUAL = 0x0205;
  17162. // Stencil Actions Constants.
  17163. /** Passed to stencilOperation to specify that stencil value must be kept */
  17164. Engine.KEEP = 0x1E00;
  17165. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17166. Engine.REPLACE = 0x1E01;
  17167. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17168. Engine.INCR = 0x1E02;
  17169. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17170. Engine.DECR = 0x1E03;
  17171. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17172. Engine.INVERT = 0x150A;
  17173. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17174. Engine.INCR_WRAP = 0x8507;
  17175. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17176. Engine.DECR_WRAP = 0x8508;
  17177. /** Texture is not repeating outside of 0..1 UVs */
  17178. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17179. /** Texture is repeating outside of 0..1 UVs */
  17180. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17181. /** Texture is repeating and mirrored */
  17182. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17183. /** ALPHA */
  17184. Engine.TEXTUREFORMAT_ALPHA = 0;
  17185. /** LUMINANCE */
  17186. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17187. /** LUMINANCE_ALPHA */
  17188. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17189. /** RGB */
  17190. Engine.TEXTUREFORMAT_RGB = 4;
  17191. /** RGBA */
  17192. Engine.TEXTUREFORMAT_RGBA = 5;
  17193. /** R */
  17194. Engine.TEXTUREFORMAT_R = 6;
  17195. /** RG */
  17196. Engine.TEXTUREFORMAT_RG = 7;
  17197. /** UNSIGNED_INT */
  17198. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17199. /** FLOAT */
  17200. Engine.TEXTURETYPE_FLOAT = 1;
  17201. /** HALF_FLOAT */
  17202. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17203. /** nearest is mag = nearest and min = nearest and mip = linear */
  17204. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17205. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17206. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17207. /** Trilinear is mag = linear and min = linear and mip = linear */
  17208. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17209. /** nearest is mag = nearest and min = nearest and mip = linear */
  17210. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17211. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17212. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17213. /** Trilinear is mag = linear and min = linear and mip = linear */
  17214. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17215. /** mag = nearest and min = nearest and mip = nearest */
  17216. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17217. /** mag = nearest and min = linear and mip = nearest */
  17218. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17219. /** mag = nearest and min = linear and mip = linear */
  17220. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17221. /** mag = nearest and min = linear and mip = none */
  17222. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17223. /** mag = nearest and min = nearest and mip = none */
  17224. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17225. /** mag = linear and min = nearest and mip = nearest */
  17226. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17227. /** mag = linear and min = nearest and mip = linear */
  17228. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17229. /** mag = linear and min = linear and mip = none */
  17230. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17231. /** mag = linear and min = nearest and mip = none */
  17232. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17233. /** Explicit coordinates mode */
  17234. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17235. /** Spherical coordinates mode */
  17236. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17237. /** Planar coordinates mode */
  17238. Engine.TEXTURE_PLANAR_MODE = 2;
  17239. /** Cubic coordinates mode */
  17240. Engine.TEXTURE_CUBIC_MODE = 3;
  17241. /** Projection coordinates mode */
  17242. Engine.TEXTURE_PROJECTION_MODE = 4;
  17243. /** Skybox coordinates mode */
  17244. Engine.TEXTURE_SKYBOX_MODE = 5;
  17245. /** Inverse Cubic coordinates mode */
  17246. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17247. /** Equirectangular coordinates mode */
  17248. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17249. /** Equirectangular Fixed coordinates mode */
  17250. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17251. /** Equirectangular Fixed Mirrored coordinates mode */
  17252. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17253. // Texture rescaling mode
  17254. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17255. Engine.SCALEMODE_FLOOR = 1;
  17256. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17257. Engine.SCALEMODE_NEAREST = 2;
  17258. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17259. Engine.SCALEMODE_CEILING = 3;
  17260. // Updatable statics so stick with vars here
  17261. /**
  17262. * Gets or sets the epsilon value used by collision engine
  17263. */
  17264. Engine.CollisionsEpsilon = 0.001;
  17265. /**
  17266. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17267. */
  17268. Engine.CodeRepository = "src/";
  17269. /**
  17270. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17271. */
  17272. Engine.ShadersRepository = "src/Shaders/";
  17273. return Engine;
  17274. }());
  17275. BABYLON.Engine = Engine;
  17276. })(BABYLON || (BABYLON = {}));
  17277. //# sourceMappingURL=babylon.engine.js.map
  17278. var BABYLON;
  17279. (function (BABYLON) {
  17280. /**
  17281. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17282. */
  17283. var Node = /** @class */ (function () {
  17284. /**
  17285. * Creates a new Node
  17286. * @param {string} name - the name and id to be given to this node
  17287. * @param {BABYLON.Scene} the scene this node will be added to
  17288. */
  17289. function Node(name, scene) {
  17290. if (scene === void 0) { scene = null; }
  17291. /**
  17292. * Gets or sets a string used to store user defined state for the node
  17293. */
  17294. this.state = "";
  17295. /**
  17296. * Gets or sets an object used to store user defined information for the node
  17297. */
  17298. this.metadata = null;
  17299. /**
  17300. * Gets or sets a boolean used to define if the node must be serialized
  17301. */
  17302. this.doNotSerialize = false;
  17303. /** @hidden */
  17304. this._isDisposed = false;
  17305. /**
  17306. * Gets a list of Animations associated with the node
  17307. */
  17308. this.animations = new Array();
  17309. this._ranges = {};
  17310. this._isEnabled = true;
  17311. this._isReady = true;
  17312. /** @hidden */
  17313. this._currentRenderId = -1;
  17314. this._parentRenderId = -1;
  17315. this._childRenderId = -1;
  17316. this._animationPropertiesOverride = null;
  17317. /**
  17318. * An event triggered when the mesh is disposed
  17319. */
  17320. this.onDisposeObservable = new BABYLON.Observable();
  17321. // Behaviors
  17322. this._behaviors = new Array();
  17323. this.name = name;
  17324. this.id = name;
  17325. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17326. this.uniqueId = this._scene.getUniqueId();
  17327. this._initCache();
  17328. }
  17329. /**
  17330. * Add a new node constructor
  17331. * @param type defines the type name of the node to construct
  17332. * @param constructorFunc defines the constructor function
  17333. */
  17334. Node.AddNodeConstructor = function (type, constructorFunc) {
  17335. this._NodeConstructors[type] = constructorFunc;
  17336. };
  17337. /**
  17338. * Returns a node constructor based on type name
  17339. * @param type defines the type name
  17340. * @param name defines the new node name
  17341. * @param scene defines the hosting scene
  17342. * @param options defines optional options to transmit to constructors
  17343. * @returns the new constructor or null
  17344. */
  17345. Node.Construct = function (type, name, scene, options) {
  17346. var constructorFunc = this._NodeConstructors[type];
  17347. if (!constructorFunc) {
  17348. return null;
  17349. }
  17350. return constructorFunc(name, scene, options);
  17351. };
  17352. /**
  17353. * Gets a boolean indicating if the node has been disposed
  17354. * @returns true if the node was disposed
  17355. */
  17356. Node.prototype.isDisposed = function () {
  17357. return this._isDisposed;
  17358. };
  17359. Object.defineProperty(Node.prototype, "parent", {
  17360. get: function () {
  17361. return this._parentNode;
  17362. },
  17363. /**
  17364. * Gets or sets the parent of the node
  17365. */
  17366. set: function (parent) {
  17367. if (this._parentNode === parent) {
  17368. return;
  17369. }
  17370. // Remove self from list of children of parent
  17371. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17372. var index = this._parentNode._children.indexOf(this);
  17373. if (index !== -1) {
  17374. this._parentNode._children.splice(index, 1);
  17375. }
  17376. }
  17377. // Store new parent
  17378. this._parentNode = parent;
  17379. // Add as child to new parent
  17380. if (this._parentNode) {
  17381. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17382. this._parentNode._children = new Array();
  17383. }
  17384. this._parentNode._children.push(this);
  17385. }
  17386. },
  17387. enumerable: true,
  17388. configurable: true
  17389. });
  17390. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17391. /**
  17392. * Gets or sets the animation properties override
  17393. */
  17394. get: function () {
  17395. if (!this._animationPropertiesOverride) {
  17396. return this._scene.animationPropertiesOverride;
  17397. }
  17398. return this._animationPropertiesOverride;
  17399. },
  17400. set: function (value) {
  17401. this._animationPropertiesOverride = value;
  17402. },
  17403. enumerable: true,
  17404. configurable: true
  17405. });
  17406. /**
  17407. * Gets a string idenfifying the name of the class
  17408. * @returns "Node" string
  17409. */
  17410. Node.prototype.getClassName = function () {
  17411. return "Node";
  17412. };
  17413. Object.defineProperty(Node.prototype, "onDispose", {
  17414. /**
  17415. * Sets a callback that will be raised when the node will be disposed
  17416. */
  17417. set: function (callback) {
  17418. if (this._onDisposeObserver) {
  17419. this.onDisposeObservable.remove(this._onDisposeObserver);
  17420. }
  17421. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17422. },
  17423. enumerable: true,
  17424. configurable: true
  17425. });
  17426. /**
  17427. * Gets the scene of the node
  17428. * @returns a {BABYLON.Scene}
  17429. */
  17430. Node.prototype.getScene = function () {
  17431. return this._scene;
  17432. };
  17433. /**
  17434. * Gets the engine of the node
  17435. * @returns a {BABYLON.Engine}
  17436. */
  17437. Node.prototype.getEngine = function () {
  17438. return this._scene.getEngine();
  17439. };
  17440. /**
  17441. * Attach a behavior to the node
  17442. * @see http://doc.babylonjs.com/features/behaviour
  17443. * @param behavior defines the behavior to attach
  17444. * @returns the current Node
  17445. */
  17446. Node.prototype.addBehavior = function (behavior) {
  17447. var _this = this;
  17448. var index = this._behaviors.indexOf(behavior);
  17449. if (index !== -1) {
  17450. return this;
  17451. }
  17452. behavior.init();
  17453. if (this._scene.isLoading) {
  17454. // We defer the attach when the scene will be loaded
  17455. this._scene.onDataLoadedObservable.addOnce(function () {
  17456. behavior.attach(_this);
  17457. });
  17458. }
  17459. else {
  17460. behavior.attach(this);
  17461. }
  17462. this._behaviors.push(behavior);
  17463. return this;
  17464. };
  17465. /**
  17466. * Remove an attached behavior
  17467. * @see http://doc.babylonjs.com/features/behaviour
  17468. * @param behavior defines the behavior to attach
  17469. * @returns the current Node
  17470. */
  17471. Node.prototype.removeBehavior = function (behavior) {
  17472. var index = this._behaviors.indexOf(behavior);
  17473. if (index === -1) {
  17474. return this;
  17475. }
  17476. this._behaviors[index].detach();
  17477. this._behaviors.splice(index, 1);
  17478. return this;
  17479. };
  17480. Object.defineProperty(Node.prototype, "behaviors", {
  17481. /**
  17482. * Gets the list of attached behaviors
  17483. * @see http://doc.babylonjs.com/features/behaviour
  17484. */
  17485. get: function () {
  17486. return this._behaviors;
  17487. },
  17488. enumerable: true,
  17489. configurable: true
  17490. });
  17491. /**
  17492. * Gets an attached behavior by name
  17493. * @param name defines the name of the behavior to look for
  17494. * @see http://doc.babylonjs.com/features/behaviour
  17495. * @returns null if behavior was not found else the requested behavior
  17496. */
  17497. Node.prototype.getBehaviorByName = function (name) {
  17498. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17499. var behavior = _a[_i];
  17500. if (behavior.name === name) {
  17501. return behavior;
  17502. }
  17503. }
  17504. return null;
  17505. };
  17506. /**
  17507. * Returns the world matrix of the node
  17508. * @returns a matrix containing the node's world matrix
  17509. */
  17510. Node.prototype.getWorldMatrix = function () {
  17511. return BABYLON.Matrix.Identity();
  17512. };
  17513. /** @hidden */
  17514. Node.prototype._getWorldMatrixDeterminant = function () {
  17515. return 1;
  17516. };
  17517. // override it in derived class if you add new variables to the cache
  17518. // and call the parent class method
  17519. /** @hidden */
  17520. Node.prototype._initCache = function () {
  17521. this._cache = {};
  17522. this._cache.parent = undefined;
  17523. };
  17524. /** @hidden */
  17525. Node.prototype.updateCache = function (force) {
  17526. if (!force && this.isSynchronized())
  17527. return;
  17528. this._cache.parent = this.parent;
  17529. this._updateCache();
  17530. };
  17531. // override it in derived class if you add new variables to the cache
  17532. // and call the parent class method if !ignoreParentClass
  17533. /** @hidden */
  17534. Node.prototype._updateCache = function (ignoreParentClass) {
  17535. };
  17536. // override it in derived class if you add new variables to the cache
  17537. /** @hidden */
  17538. Node.prototype._isSynchronized = function () {
  17539. return true;
  17540. };
  17541. /** @hidden */
  17542. Node.prototype._markSyncedWithParent = function () {
  17543. if (this.parent) {
  17544. this._parentRenderId = this.parent._childRenderId;
  17545. }
  17546. };
  17547. /** @hidden */
  17548. Node.prototype.isSynchronizedWithParent = function () {
  17549. if (!this.parent) {
  17550. return true;
  17551. }
  17552. if (this._parentRenderId !== this.parent._childRenderId) {
  17553. return false;
  17554. }
  17555. return this.parent.isSynchronized();
  17556. };
  17557. /** @hidden */
  17558. Node.prototype.isSynchronized = function (updateCache) {
  17559. var check = this.hasNewParent();
  17560. check = check || !this.isSynchronizedWithParent();
  17561. check = check || !this._isSynchronized();
  17562. if (updateCache)
  17563. this.updateCache(true);
  17564. return !check;
  17565. };
  17566. /** @hidden */
  17567. Node.prototype.hasNewParent = function (update) {
  17568. if (this._cache.parent === this.parent)
  17569. return false;
  17570. if (update)
  17571. this._cache.parent = this.parent;
  17572. return true;
  17573. };
  17574. /**
  17575. * Is this node ready to be used/rendered
  17576. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17577. * @return true if the node is ready
  17578. */
  17579. Node.prototype.isReady = function (completeCheck) {
  17580. if (completeCheck === void 0) { completeCheck = false; }
  17581. return this._isReady;
  17582. };
  17583. /**
  17584. * Is this node enabled?
  17585. * 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
  17586. * @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
  17587. * @return whether this node (and its parent) is enabled
  17588. */
  17589. Node.prototype.isEnabled = function (checkAncestors) {
  17590. if (checkAncestors === void 0) { checkAncestors = true; }
  17591. if (checkAncestors === false) {
  17592. return this._isEnabled;
  17593. }
  17594. if (this._isEnabled === false) {
  17595. return false;
  17596. }
  17597. if (this.parent !== undefined && this.parent !== null) {
  17598. return this.parent.isEnabled(checkAncestors);
  17599. }
  17600. return true;
  17601. };
  17602. /**
  17603. * Set the enabled state of this node
  17604. * @param value defines the new enabled state
  17605. */
  17606. Node.prototype.setEnabled = function (value) {
  17607. this._isEnabled = value;
  17608. };
  17609. /**
  17610. * Is this node a descendant of the given node?
  17611. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17612. * @param ancestor defines the parent node to inspect
  17613. * @returns a boolean indicating if this node is a descendant of the given node
  17614. */
  17615. Node.prototype.isDescendantOf = function (ancestor) {
  17616. if (this.parent) {
  17617. if (this.parent === ancestor) {
  17618. return true;
  17619. }
  17620. return this.parent.isDescendantOf(ancestor);
  17621. }
  17622. return false;
  17623. };
  17624. /** @hidden */
  17625. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17626. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17627. if (!this._children) {
  17628. return;
  17629. }
  17630. for (var index = 0; index < this._children.length; index++) {
  17631. var item = this._children[index];
  17632. if (!predicate || predicate(item)) {
  17633. results.push(item);
  17634. }
  17635. if (!directDescendantsOnly) {
  17636. item._getDescendants(results, false, predicate);
  17637. }
  17638. }
  17639. };
  17640. /**
  17641. * Will return all nodes that have this node as ascendant
  17642. * @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
  17643. * @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
  17644. * @return all children nodes of all types
  17645. */
  17646. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17647. var results = new Array();
  17648. this._getDescendants(results, directDescendantsOnly, predicate);
  17649. return results;
  17650. };
  17651. /**
  17652. * Get all child-meshes of this node
  17653. * @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
  17654. * @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
  17655. * @returns an array of {BABYLON.AbstractMesh}
  17656. */
  17657. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17658. var results = [];
  17659. this._getDescendants(results, directDescendantsOnly, function (node) {
  17660. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17661. });
  17662. return results;
  17663. };
  17664. /**
  17665. * Get all child-transformNodes of this node
  17666. * @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
  17667. * @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
  17668. * @returns an array of {BABYLON.TransformNode}
  17669. */
  17670. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17671. var results = [];
  17672. this._getDescendants(results, directDescendantsOnly, function (node) {
  17673. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17674. });
  17675. return results;
  17676. };
  17677. /**
  17678. * Get all direct children of this node
  17679. * @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
  17680. * @returns an array of {BABYLON.Node}
  17681. */
  17682. Node.prototype.getChildren = function (predicate) {
  17683. return this.getDescendants(true, predicate);
  17684. };
  17685. /** @hidden */
  17686. Node.prototype._setReady = function (state) {
  17687. if (state === this._isReady) {
  17688. return;
  17689. }
  17690. if (!state) {
  17691. this._isReady = false;
  17692. return;
  17693. }
  17694. if (this.onReady) {
  17695. this.onReady(this);
  17696. }
  17697. this._isReady = true;
  17698. };
  17699. /**
  17700. * Get an animation by name
  17701. * @param name defines the name of the animation to look for
  17702. * @returns null if not found else the requested animation
  17703. */
  17704. Node.prototype.getAnimationByName = function (name) {
  17705. for (var i = 0; i < this.animations.length; i++) {
  17706. var animation = this.animations[i];
  17707. if (animation.name === name) {
  17708. return animation;
  17709. }
  17710. }
  17711. return null;
  17712. };
  17713. /**
  17714. * Creates an animation range for this node
  17715. * @param name defines the name of the range
  17716. * @param from defines the starting key
  17717. * @param to defines the end key
  17718. */
  17719. Node.prototype.createAnimationRange = function (name, from, to) {
  17720. // check name not already in use
  17721. if (!this._ranges[name]) {
  17722. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17723. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17724. if (this.animations[i]) {
  17725. this.animations[i].createRange(name, from, to);
  17726. }
  17727. }
  17728. }
  17729. };
  17730. /**
  17731. * Delete a specific animation range
  17732. * @param name defines the name of the range to delete
  17733. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17734. */
  17735. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17736. if (deleteFrames === void 0) { deleteFrames = true; }
  17737. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17738. if (this.animations[i]) {
  17739. this.animations[i].deleteRange(name, deleteFrames);
  17740. }
  17741. }
  17742. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17743. };
  17744. /**
  17745. * Get an animation range by name
  17746. * @param name defines the name of the animation range to look for
  17747. * @returns null if not found else the requested animation range
  17748. */
  17749. Node.prototype.getAnimationRange = function (name) {
  17750. return this._ranges[name];
  17751. };
  17752. /**
  17753. * Will start the animation sequence
  17754. * @param name defines the range frames for animation sequence
  17755. * @param loop defines if the animation should loop (false by default)
  17756. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17757. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17758. * @returns the object created for this animation. If range does not exist, it will return null
  17759. */
  17760. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17761. var range = this.getAnimationRange(name);
  17762. if (!range) {
  17763. return null;
  17764. }
  17765. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17766. };
  17767. /**
  17768. * Serialize animation ranges into a JSON compatible object
  17769. * @returns serialization object
  17770. */
  17771. Node.prototype.serializeAnimationRanges = function () {
  17772. var serializationRanges = [];
  17773. for (var name in this._ranges) {
  17774. var localRange = this._ranges[name];
  17775. if (!localRange) {
  17776. continue;
  17777. }
  17778. var range = {};
  17779. range.name = name;
  17780. range.from = localRange.from;
  17781. range.to = localRange.to;
  17782. serializationRanges.push(range);
  17783. }
  17784. return serializationRanges;
  17785. };
  17786. /**
  17787. * Computes the world matrix of the node
  17788. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17789. * @returns the world matrix
  17790. */
  17791. Node.prototype.computeWorldMatrix = function (force) {
  17792. return BABYLON.Matrix.Identity();
  17793. };
  17794. /**
  17795. * Releases resources associated with this node.
  17796. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17797. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17798. */
  17799. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17800. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17801. if (!doNotRecurse) {
  17802. var nodes = this.getDescendants(true);
  17803. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17804. var node = nodes_1[_i];
  17805. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17806. }
  17807. }
  17808. else {
  17809. var transformNodes = this.getChildTransformNodes(true);
  17810. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17811. var transformNode = transformNodes_1[_a];
  17812. transformNode.parent = null;
  17813. transformNode.computeWorldMatrix(true);
  17814. }
  17815. }
  17816. this.parent = null;
  17817. // Callback
  17818. this.onDisposeObservable.notifyObservers(this);
  17819. this.onDisposeObservable.clear();
  17820. // Behaviors
  17821. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17822. var behavior = _c[_b];
  17823. behavior.detach();
  17824. }
  17825. this._behaviors = [];
  17826. this._isDisposed = true;
  17827. };
  17828. /**
  17829. * Parse animation range data from a serialization object and store them into a given node
  17830. * @param node defines where to store the animation ranges
  17831. * @param parsedNode defines the serialization object to read data from
  17832. * @param scene defines the hosting scene
  17833. */
  17834. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17835. if (parsedNode.ranges) {
  17836. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17837. var data = parsedNode.ranges[index];
  17838. node.createAnimationRange(data.name, data.from, data.to);
  17839. }
  17840. }
  17841. };
  17842. Node._NodeConstructors = {};
  17843. __decorate([
  17844. BABYLON.serialize()
  17845. ], Node.prototype, "name", void 0);
  17846. __decorate([
  17847. BABYLON.serialize()
  17848. ], Node.prototype, "id", void 0);
  17849. __decorate([
  17850. BABYLON.serialize()
  17851. ], Node.prototype, "uniqueId", void 0);
  17852. __decorate([
  17853. BABYLON.serialize()
  17854. ], Node.prototype, "state", void 0);
  17855. __decorate([
  17856. BABYLON.serialize()
  17857. ], Node.prototype, "metadata", void 0);
  17858. return Node;
  17859. }());
  17860. BABYLON.Node = Node;
  17861. })(BABYLON || (BABYLON = {}));
  17862. //# sourceMappingURL=babylon.node.js.map
  17863. var BABYLON;
  17864. (function (BABYLON) {
  17865. var BoundingSphere = /** @class */ (function () {
  17866. /**
  17867. * Creates a new bounding sphere
  17868. * @param min defines the minimum vector (in local space)
  17869. * @param max defines the maximum vector (in local space)
  17870. */
  17871. function BoundingSphere(min, max) {
  17872. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17873. this.reConstruct(min, max);
  17874. }
  17875. /**
  17876. * Recreates the entire bounding sphere from scratch
  17877. * @param min defines the new minimum vector (in local space)
  17878. * @param max defines the new maximum vector (in local space)
  17879. */
  17880. BoundingSphere.prototype.reConstruct = function (min, max) {
  17881. this.minimum = min.clone();
  17882. this.maximum = max.clone();
  17883. var distance = BABYLON.Vector3.Distance(min, max);
  17884. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17885. this.radius = distance * 0.5;
  17886. this.centerWorld = BABYLON.Vector3.Zero();
  17887. this._update(BABYLON.Matrix.Identity());
  17888. };
  17889. /**
  17890. * Scale the current bounding sphere by applying a scale factor
  17891. * @param factor defines the scale factor to apply
  17892. * @returns the current bounding box
  17893. */
  17894. BoundingSphere.prototype.scale = function (factor) {
  17895. var newRadius = this.radius * factor;
  17896. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17897. var min = this.center.subtract(newRadiusVector);
  17898. var max = this.center.add(newRadiusVector);
  17899. this.reConstruct(min, max);
  17900. return this;
  17901. };
  17902. // Methods
  17903. /** @hidden */
  17904. BoundingSphere.prototype._update = function (world) {
  17905. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17906. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17907. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17908. };
  17909. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17910. for (var i = 0; i < 6; i++) {
  17911. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17912. return false;
  17913. }
  17914. return true;
  17915. };
  17916. BoundingSphere.prototype.intersectsPoint = function (point) {
  17917. var x = this.centerWorld.x - point.x;
  17918. var y = this.centerWorld.y - point.y;
  17919. var z = this.centerWorld.z - point.z;
  17920. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17921. if (this.radiusWorld < distance)
  17922. return false;
  17923. return true;
  17924. };
  17925. // Statics
  17926. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17927. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17928. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17929. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17930. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17931. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17932. return false;
  17933. return true;
  17934. };
  17935. return BoundingSphere;
  17936. }());
  17937. BABYLON.BoundingSphere = BoundingSphere;
  17938. })(BABYLON || (BABYLON = {}));
  17939. //# sourceMappingURL=babylon.boundingSphere.js.map
  17940. var BABYLON;
  17941. (function (BABYLON) {
  17942. var BoundingBox = /** @class */ (function () {
  17943. /**
  17944. * Creates a new bounding box
  17945. * @param min defines the minimum vector (in local space)
  17946. * @param max defines the maximum vector (in local space)
  17947. */
  17948. function BoundingBox(min, max) {
  17949. this.vectorsWorld = new Array();
  17950. this.reConstruct(min, max);
  17951. }
  17952. // Methods
  17953. /**
  17954. * Recreates the entire bounding box from scratch
  17955. * @param min defines the new minimum vector (in local space)
  17956. * @param max defines the new maximum vector (in local space)
  17957. */
  17958. BoundingBox.prototype.reConstruct = function (min, max) {
  17959. this.minimum = min.clone();
  17960. this.maximum = max.clone();
  17961. // Bounding vectors
  17962. this.vectors = new Array();
  17963. this.vectors.push(this.minimum.clone());
  17964. this.vectors.push(this.maximum.clone());
  17965. this.vectors.push(this.minimum.clone());
  17966. this.vectors[2].x = this.maximum.x;
  17967. this.vectors.push(this.minimum.clone());
  17968. this.vectors[3].y = this.maximum.y;
  17969. this.vectors.push(this.minimum.clone());
  17970. this.vectors[4].z = this.maximum.z;
  17971. this.vectors.push(this.maximum.clone());
  17972. this.vectors[5].z = this.minimum.z;
  17973. this.vectors.push(this.maximum.clone());
  17974. this.vectors[6].x = this.minimum.x;
  17975. this.vectors.push(this.maximum.clone());
  17976. this.vectors[7].y = this.minimum.y;
  17977. // OBB
  17978. this.center = this.maximum.add(this.minimum).scale(0.5);
  17979. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17980. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17981. // World
  17982. for (var index = 0; index < this.vectors.length; index++) {
  17983. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17984. }
  17985. this.minimumWorld = BABYLON.Vector3.Zero();
  17986. this.maximumWorld = BABYLON.Vector3.Zero();
  17987. this.centerWorld = BABYLON.Vector3.Zero();
  17988. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17989. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17990. };
  17991. /**
  17992. * Scale the current bounding box by applying a scale factor
  17993. * @param factor defines the scale factor to apply
  17994. * @returns the current bounding box
  17995. */
  17996. BoundingBox.prototype.scale = function (factor) {
  17997. var diff = this.maximum.subtract(this.minimum);
  17998. var distance = diff.length() * factor;
  17999. diff.normalize();
  18000. var newRadius = diff.scale(distance / 2);
  18001. var min = this.center.subtract(newRadius);
  18002. var max = this.center.add(newRadius);
  18003. this.reConstruct(min, max);
  18004. return this;
  18005. };
  18006. BoundingBox.prototype.getWorldMatrix = function () {
  18007. return this._worldMatrix;
  18008. };
  18009. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18010. this._worldMatrix.copyFrom(matrix);
  18011. return this;
  18012. };
  18013. /** @hidden */
  18014. BoundingBox.prototype._update = function (world) {
  18015. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18016. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18017. for (var index = 0; index < this.vectors.length; index++) {
  18018. var v = this.vectorsWorld[index];
  18019. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18020. if (v.x < this.minimumWorld.x)
  18021. this.minimumWorld.x = v.x;
  18022. if (v.y < this.minimumWorld.y)
  18023. this.minimumWorld.y = v.y;
  18024. if (v.z < this.minimumWorld.z)
  18025. this.minimumWorld.z = v.z;
  18026. if (v.x > this.maximumWorld.x)
  18027. this.maximumWorld.x = v.x;
  18028. if (v.y > this.maximumWorld.y)
  18029. this.maximumWorld.y = v.y;
  18030. if (v.z > this.maximumWorld.z)
  18031. this.maximumWorld.z = v.z;
  18032. }
  18033. // Extend
  18034. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18035. this.extendSizeWorld.scaleInPlace(0.5);
  18036. // OBB
  18037. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18038. this.centerWorld.scaleInPlace(0.5);
  18039. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18040. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18041. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18042. this._worldMatrix = world;
  18043. };
  18044. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18045. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18046. };
  18047. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18048. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18049. };
  18050. BoundingBox.prototype.intersectsPoint = function (point) {
  18051. var delta = -BABYLON.Epsilon;
  18052. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18053. return false;
  18054. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18055. return false;
  18056. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18057. return false;
  18058. return true;
  18059. };
  18060. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18061. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18062. };
  18063. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18064. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18065. return false;
  18066. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18067. return false;
  18068. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18069. return false;
  18070. return true;
  18071. };
  18072. // Statics
  18073. BoundingBox.Intersects = function (box0, box1) {
  18074. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18075. return false;
  18076. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18077. return false;
  18078. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18079. return false;
  18080. return true;
  18081. };
  18082. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18083. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18084. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18085. return (num <= (sphereRadius * sphereRadius));
  18086. };
  18087. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18088. for (var p = 0; p < 6; p++) {
  18089. for (var i = 0; i < 8; i++) {
  18090. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18091. return false;
  18092. }
  18093. }
  18094. }
  18095. return true;
  18096. };
  18097. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18098. for (var p = 0; p < 6; p++) {
  18099. var inCount = 8;
  18100. for (var i = 0; i < 8; i++) {
  18101. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18102. --inCount;
  18103. }
  18104. else {
  18105. break;
  18106. }
  18107. }
  18108. if (inCount === 0)
  18109. return false;
  18110. }
  18111. return true;
  18112. };
  18113. return BoundingBox;
  18114. }());
  18115. BABYLON.BoundingBox = BoundingBox;
  18116. })(BABYLON || (BABYLON = {}));
  18117. //# sourceMappingURL=babylon.boundingBox.js.map
  18118. var BABYLON;
  18119. (function (BABYLON) {
  18120. var computeBoxExtents = function (axis, box) {
  18121. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18122. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18123. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18124. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18125. var r = r0 + r1 + r2;
  18126. return {
  18127. min: p - r,
  18128. max: p + r
  18129. };
  18130. };
  18131. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18132. var axisOverlap = function (axis, box0, box1) {
  18133. var result0 = computeBoxExtents(axis, box0);
  18134. var result1 = computeBoxExtents(axis, box1);
  18135. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18136. };
  18137. var BoundingInfo = /** @class */ (function () {
  18138. function BoundingInfo(minimum, maximum) {
  18139. this.minimum = minimum;
  18140. this.maximum = maximum;
  18141. this._isLocked = false;
  18142. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18143. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18144. }
  18145. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18146. get: function () {
  18147. return this._isLocked;
  18148. },
  18149. set: function (value) {
  18150. this._isLocked = value;
  18151. },
  18152. enumerable: true,
  18153. configurable: true
  18154. });
  18155. // Methods
  18156. BoundingInfo.prototype.update = function (world) {
  18157. if (this._isLocked) {
  18158. return;
  18159. }
  18160. this.boundingBox._update(world);
  18161. this.boundingSphere._update(world);
  18162. };
  18163. /**
  18164. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18165. * @param center New center of the bounding info
  18166. * @param extend New extend of the bounding info
  18167. */
  18168. BoundingInfo.prototype.centerOn = function (center, extend) {
  18169. this.minimum = center.subtract(extend);
  18170. this.maximum = center.add(extend);
  18171. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18172. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18173. return this;
  18174. };
  18175. /**
  18176. * Scale the current bounding info by applying a scale factor
  18177. * @param factor defines the scale factor to apply
  18178. * @returns the current bounding info
  18179. */
  18180. BoundingInfo.prototype.scale = function (factor) {
  18181. this.boundingBox.scale(factor);
  18182. this.boundingSphere.scale(factor);
  18183. return this;
  18184. };
  18185. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18186. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18187. return false;
  18188. return this.boundingBox.isInFrustum(frustumPlanes);
  18189. };
  18190. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18191. /**
  18192. * Gets the world distance between the min and max points of the bounding box
  18193. */
  18194. get: function () {
  18195. var boundingBox = this.boundingBox;
  18196. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18197. return size.length();
  18198. },
  18199. enumerable: true,
  18200. configurable: true
  18201. });
  18202. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18203. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18204. };
  18205. /** @hidden */
  18206. BoundingInfo.prototype._checkCollision = function (collider) {
  18207. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18208. };
  18209. BoundingInfo.prototype.intersectsPoint = function (point) {
  18210. if (!this.boundingSphere.centerWorld) {
  18211. return false;
  18212. }
  18213. if (!this.boundingSphere.intersectsPoint(point)) {
  18214. return false;
  18215. }
  18216. if (!this.boundingBox.intersectsPoint(point)) {
  18217. return false;
  18218. }
  18219. return true;
  18220. };
  18221. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18222. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18223. return false;
  18224. }
  18225. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18226. return false;
  18227. }
  18228. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18229. return false;
  18230. }
  18231. if (!precise) {
  18232. return true;
  18233. }
  18234. var box0 = this.boundingBox;
  18235. var box1 = boundingInfo.boundingBox;
  18236. if (!axisOverlap(box0.directions[0], box0, box1))
  18237. return false;
  18238. if (!axisOverlap(box0.directions[1], box0, box1))
  18239. return false;
  18240. if (!axisOverlap(box0.directions[2], box0, box1))
  18241. return false;
  18242. if (!axisOverlap(box1.directions[0], box0, box1))
  18243. return false;
  18244. if (!axisOverlap(box1.directions[1], box0, box1))
  18245. return false;
  18246. if (!axisOverlap(box1.directions[2], box0, box1))
  18247. return false;
  18248. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18249. return false;
  18250. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18251. return false;
  18252. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18253. return false;
  18254. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18255. return false;
  18256. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18257. return false;
  18258. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18259. return false;
  18260. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18261. return false;
  18262. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18263. return false;
  18264. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18265. return false;
  18266. return true;
  18267. };
  18268. return BoundingInfo;
  18269. }());
  18270. BABYLON.BoundingInfo = BoundingInfo;
  18271. })(BABYLON || (BABYLON = {}));
  18272. //# sourceMappingURL=babylon.boundingInfo.js.map
  18273. var BABYLON;
  18274. (function (BABYLON) {
  18275. var TransformNode = /** @class */ (function (_super) {
  18276. __extends(TransformNode, _super);
  18277. function TransformNode(name, scene, isPure) {
  18278. if (scene === void 0) { scene = null; }
  18279. if (isPure === void 0) { isPure = true; }
  18280. var _this = _super.call(this, name, scene) || this;
  18281. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18282. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18283. _this._up = new BABYLON.Vector3(0, 1, 0);
  18284. _this._right = new BABYLON.Vector3(1, 0, 0);
  18285. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18286. // Properties
  18287. _this._rotation = BABYLON.Vector3.Zero();
  18288. _this._scaling = BABYLON.Vector3.One();
  18289. _this._isDirty = false;
  18290. /**
  18291. * Set the billboard mode. Default is 0.
  18292. *
  18293. * | Value | Type | Description |
  18294. * | --- | --- | --- |
  18295. * | 0 | BILLBOARDMODE_NONE | |
  18296. * | 1 | BILLBOARDMODE_X | |
  18297. * | 2 | BILLBOARDMODE_Y | |
  18298. * | 4 | BILLBOARDMODE_Z | |
  18299. * | 7 | BILLBOARDMODE_ALL | |
  18300. *
  18301. */
  18302. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18303. _this.scalingDeterminant = 1;
  18304. _this.infiniteDistance = false;
  18305. /**
  18306. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18307. * By default the system will update normals to compensate
  18308. */
  18309. _this.ignoreNonUniformScaling = false;
  18310. _this.position = BABYLON.Vector3.Zero();
  18311. _this._localWorld = BABYLON.Matrix.Zero();
  18312. /** @hidden */
  18313. _this._worldMatrix = BABYLON.Matrix.Zero();
  18314. /** @hidden */
  18315. _this._worldMatrixDeterminant = 0;
  18316. _this._absolutePosition = BABYLON.Vector3.Zero();
  18317. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18318. _this._postMultiplyPivotMatrix = false;
  18319. _this._isWorldMatrixFrozen = false;
  18320. /**
  18321. * An event triggered after the world matrix is updated
  18322. */
  18323. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18324. _this._nonUniformScaling = false;
  18325. if (isPure) {
  18326. _this.getScene().addTransformNode(_this);
  18327. }
  18328. return _this;
  18329. }
  18330. /**
  18331. * Gets a string identifying the name of the class
  18332. * @returns "TransformNode" string
  18333. */
  18334. TransformNode.prototype.getClassName = function () {
  18335. return "TransformNode";
  18336. };
  18337. Object.defineProperty(TransformNode.prototype, "rotation", {
  18338. /**
  18339. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18340. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18341. * Default : (0.0, 0.0, 0.0)
  18342. */
  18343. get: function () {
  18344. return this._rotation;
  18345. },
  18346. set: function (newRotation) {
  18347. this._rotation = newRotation;
  18348. },
  18349. enumerable: true,
  18350. configurable: true
  18351. });
  18352. Object.defineProperty(TransformNode.prototype, "scaling", {
  18353. /**
  18354. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18355. * Default : (1.0, 1.0, 1.0)
  18356. */
  18357. get: function () {
  18358. return this._scaling;
  18359. },
  18360. /**
  18361. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18362. * Default : (1.0, 1.0, 1.0)
  18363. */
  18364. set: function (newScaling) {
  18365. this._scaling = newScaling;
  18366. },
  18367. enumerable: true,
  18368. configurable: true
  18369. });
  18370. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18371. /**
  18372. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18373. * It's null by default.
  18374. * 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)
  18375. */
  18376. get: function () {
  18377. return this._rotationQuaternion;
  18378. },
  18379. set: function (quaternion) {
  18380. this._rotationQuaternion = quaternion;
  18381. //reset the rotation vector.
  18382. if (quaternion && this.rotation.length()) {
  18383. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18384. }
  18385. },
  18386. enumerable: true,
  18387. configurable: true
  18388. });
  18389. Object.defineProperty(TransformNode.prototype, "forward", {
  18390. /**
  18391. * The forward direction of that transform in world space.
  18392. */
  18393. get: function () {
  18394. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18395. },
  18396. enumerable: true,
  18397. configurable: true
  18398. });
  18399. Object.defineProperty(TransformNode.prototype, "up", {
  18400. /**
  18401. * The up direction of that transform in world space.
  18402. */
  18403. get: function () {
  18404. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18405. },
  18406. enumerable: true,
  18407. configurable: true
  18408. });
  18409. Object.defineProperty(TransformNode.prototype, "right", {
  18410. /**
  18411. * The right direction of that transform in world space.
  18412. */
  18413. get: function () {
  18414. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18415. },
  18416. enumerable: true,
  18417. configurable: true
  18418. });
  18419. /**
  18420. * Returns the latest update of the World matrix
  18421. * Returns a Matrix.
  18422. */
  18423. TransformNode.prototype.getWorldMatrix = function () {
  18424. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18425. this.computeWorldMatrix();
  18426. }
  18427. return this._worldMatrix;
  18428. };
  18429. /** @hidden */
  18430. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18431. return this._worldMatrixDeterminant;
  18432. };
  18433. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18434. /**
  18435. * Returns directly the latest state of the mesh World matrix.
  18436. * A Matrix is returned.
  18437. */
  18438. get: function () {
  18439. return this._worldMatrix;
  18440. },
  18441. enumerable: true,
  18442. configurable: true
  18443. });
  18444. /**
  18445. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18446. * Returns the TransformNode.
  18447. */
  18448. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18449. this._poseMatrix.copyFrom(matrix);
  18450. return this;
  18451. };
  18452. /**
  18453. * Returns the mesh Pose matrix.
  18454. * Returned object : Matrix
  18455. */
  18456. TransformNode.prototype.getPoseMatrix = function () {
  18457. return this._poseMatrix;
  18458. };
  18459. /** @hidden */
  18460. TransformNode.prototype._isSynchronized = function () {
  18461. if (this._isDirty) {
  18462. return false;
  18463. }
  18464. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18465. return false;
  18466. if (this._cache.pivotMatrixUpdated) {
  18467. return false;
  18468. }
  18469. if (this.infiniteDistance) {
  18470. return false;
  18471. }
  18472. if (!this._cache.position.equals(this.position))
  18473. return false;
  18474. if (this.rotationQuaternion) {
  18475. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18476. return false;
  18477. }
  18478. if (!this._cache.rotation.equals(this.rotation))
  18479. return false;
  18480. if (!this._cache.scaling.equals(this.scaling))
  18481. return false;
  18482. return true;
  18483. };
  18484. /** @hidden */
  18485. TransformNode.prototype._initCache = function () {
  18486. _super.prototype._initCache.call(this);
  18487. this._cache.localMatrixUpdated = false;
  18488. this._cache.position = BABYLON.Vector3.Zero();
  18489. this._cache.scaling = BABYLON.Vector3.Zero();
  18490. this._cache.rotation = BABYLON.Vector3.Zero();
  18491. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18492. this._cache.billboardMode = -1;
  18493. };
  18494. TransformNode.prototype.markAsDirty = function (property) {
  18495. if (property === "rotation") {
  18496. this.rotationQuaternion = null;
  18497. }
  18498. this._currentRenderId = Number.MAX_VALUE;
  18499. this._isDirty = true;
  18500. return this;
  18501. };
  18502. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18503. /**
  18504. * Returns the current mesh absolute position.
  18505. * Returns a Vector3.
  18506. */
  18507. get: function () {
  18508. return this._absolutePosition;
  18509. },
  18510. enumerable: true,
  18511. configurable: true
  18512. });
  18513. /**
  18514. * Sets a new matrix to apply before all other transformation
  18515. * @param matrix defines the transform matrix
  18516. * @returns the current TransformNode
  18517. */
  18518. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18519. return this.setPivotMatrix(matrix, false);
  18520. };
  18521. /**
  18522. * Sets a new pivot matrix to the current node
  18523. * @param matrix defines the new pivot matrix to use
  18524. * @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
  18525. * @returns the current TransformNode
  18526. */
  18527. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18528. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18529. this._pivotMatrix = matrix.clone();
  18530. this._cache.pivotMatrixUpdated = true;
  18531. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18532. if (this._postMultiplyPivotMatrix) {
  18533. if (!this._pivotMatrixInverse) {
  18534. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18535. }
  18536. else {
  18537. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18538. }
  18539. }
  18540. return this;
  18541. };
  18542. /**
  18543. * Returns the mesh pivot matrix.
  18544. * Default : Identity.
  18545. * A Matrix is returned.
  18546. */
  18547. TransformNode.prototype.getPivotMatrix = function () {
  18548. return this._pivotMatrix;
  18549. };
  18550. /**
  18551. * Prevents the World matrix to be computed any longer.
  18552. * Returns the TransformNode.
  18553. */
  18554. TransformNode.prototype.freezeWorldMatrix = function () {
  18555. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18556. this.computeWorldMatrix(true);
  18557. this._isWorldMatrixFrozen = true;
  18558. return this;
  18559. };
  18560. /**
  18561. * Allows back the World matrix computation.
  18562. * Returns the TransformNode.
  18563. */
  18564. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18565. this._isWorldMatrixFrozen = false;
  18566. this.computeWorldMatrix(true);
  18567. return this;
  18568. };
  18569. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18570. /**
  18571. * True if the World matrix has been frozen.
  18572. * Returns a boolean.
  18573. */
  18574. get: function () {
  18575. return this._isWorldMatrixFrozen;
  18576. },
  18577. enumerable: true,
  18578. configurable: true
  18579. });
  18580. /**
  18581. * Retuns the mesh absolute position in the World.
  18582. * Returns a Vector3.
  18583. */
  18584. TransformNode.prototype.getAbsolutePosition = function () {
  18585. this.computeWorldMatrix();
  18586. return this._absolutePosition;
  18587. };
  18588. /**
  18589. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18590. * Returns the TransformNode.
  18591. */
  18592. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18593. if (!absolutePosition) {
  18594. return this;
  18595. }
  18596. var absolutePositionX;
  18597. var absolutePositionY;
  18598. var absolutePositionZ;
  18599. if (absolutePosition.x === undefined) {
  18600. if (arguments.length < 3) {
  18601. return this;
  18602. }
  18603. absolutePositionX = arguments[0];
  18604. absolutePositionY = arguments[1];
  18605. absolutePositionZ = arguments[2];
  18606. }
  18607. else {
  18608. absolutePositionX = absolutePosition.x;
  18609. absolutePositionY = absolutePosition.y;
  18610. absolutePositionZ = absolutePosition.z;
  18611. }
  18612. if (this.parent) {
  18613. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18614. invertParentWorldMatrix.invert();
  18615. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18616. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18617. }
  18618. else {
  18619. this.position.x = absolutePositionX;
  18620. this.position.y = absolutePositionY;
  18621. this.position.z = absolutePositionZ;
  18622. }
  18623. return this;
  18624. };
  18625. /**
  18626. * Sets the mesh position in its local space.
  18627. * Returns the TransformNode.
  18628. */
  18629. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18630. this.computeWorldMatrix();
  18631. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18632. return this;
  18633. };
  18634. /**
  18635. * Returns the mesh position in the local space from the current World matrix values.
  18636. * Returns a new Vector3.
  18637. */
  18638. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18639. this.computeWorldMatrix();
  18640. var invLocalWorldMatrix = this._localWorld.clone();
  18641. invLocalWorldMatrix.invert();
  18642. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18643. };
  18644. /**
  18645. * Translates the mesh along the passed Vector3 in its local space.
  18646. * Returns the TransformNode.
  18647. */
  18648. TransformNode.prototype.locallyTranslate = function (vector3) {
  18649. this.computeWorldMatrix(true);
  18650. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18651. return this;
  18652. };
  18653. /**
  18654. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18655. * @param targetPoint the position (must be in same space as current mesh) to look at
  18656. * @param yawCor optional yaw (y-axis) correction in radians
  18657. * @param pitchCor optional pitch (x-axis) correction in radians
  18658. * @param rollCor optional roll (z-axis) correction in radians
  18659. * @param space the choosen space of the target
  18660. * @returns the TransformNode.
  18661. */
  18662. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18663. if (yawCor === void 0) { yawCor = 0; }
  18664. if (pitchCor === void 0) { pitchCor = 0; }
  18665. if (rollCor === void 0) { rollCor = 0; }
  18666. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18667. var dv = TransformNode._lookAtVectorCache;
  18668. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18669. targetPoint.subtractToRef(pos, dv);
  18670. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18671. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18672. var pitch = Math.atan2(dv.y, len);
  18673. if (this.rotationQuaternion) {
  18674. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18675. }
  18676. else {
  18677. this.rotation.x = pitch + pitchCor;
  18678. this.rotation.y = yaw + yawCor;
  18679. this.rotation.z = rollCor;
  18680. }
  18681. return this;
  18682. };
  18683. /**
  18684. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18685. * This Vector3 is expressed in the World space.
  18686. */
  18687. TransformNode.prototype.getDirection = function (localAxis) {
  18688. var result = BABYLON.Vector3.Zero();
  18689. this.getDirectionToRef(localAxis, result);
  18690. return result;
  18691. };
  18692. /**
  18693. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18694. * localAxis is expressed in the mesh local space.
  18695. * result is computed in the Wordl space from the mesh World matrix.
  18696. * Returns the TransformNode.
  18697. */
  18698. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18699. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18700. return this;
  18701. };
  18702. /**
  18703. * Sets a new pivot point to the current node
  18704. * @param point defines the new pivot point to use
  18705. * @param space defines if the point is in world or local space (local by default)
  18706. * @returns the current TransformNode
  18707. */
  18708. TransformNode.prototype.setPivotPoint = function (point, space) {
  18709. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18710. if (this.getScene().getRenderId() == 0) {
  18711. this.computeWorldMatrix(true);
  18712. }
  18713. var wm = this.getWorldMatrix();
  18714. if (space == BABYLON.Space.WORLD) {
  18715. var tmat = BABYLON.Tmp.Matrix[0];
  18716. wm.invertToRef(tmat);
  18717. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18718. }
  18719. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18720. };
  18721. /**
  18722. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18723. */
  18724. TransformNode.prototype.getPivotPoint = function () {
  18725. var point = BABYLON.Vector3.Zero();
  18726. this.getPivotPointToRef(point);
  18727. return point;
  18728. };
  18729. /**
  18730. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18731. * Returns the TransformNode.
  18732. */
  18733. TransformNode.prototype.getPivotPointToRef = function (result) {
  18734. result.x = -this._pivotMatrix.m[12];
  18735. result.y = -this._pivotMatrix.m[13];
  18736. result.z = -this._pivotMatrix.m[14];
  18737. return this;
  18738. };
  18739. /**
  18740. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18741. */
  18742. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18743. var point = BABYLON.Vector3.Zero();
  18744. this.getAbsolutePivotPointToRef(point);
  18745. return point;
  18746. };
  18747. /**
  18748. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18749. * Returns the TransformNode.
  18750. */
  18751. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18752. result.x = this._pivotMatrix.m[12];
  18753. result.y = this._pivotMatrix.m[13];
  18754. result.z = this._pivotMatrix.m[14];
  18755. this.getPivotPointToRef(result);
  18756. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18757. return this;
  18758. };
  18759. /**
  18760. * Defines the passed node as the parent of the current node.
  18761. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18762. * Returns the TransformNode.
  18763. */
  18764. TransformNode.prototype.setParent = function (node) {
  18765. if (!node && !this.parent) {
  18766. return this;
  18767. }
  18768. if (!node) {
  18769. var rotation = BABYLON.Tmp.Quaternion[0];
  18770. var position = BABYLON.Tmp.Vector3[0];
  18771. var scale = BABYLON.Tmp.Vector3[1];
  18772. if (this.parent && this.parent.computeWorldMatrix) {
  18773. this.parent.computeWorldMatrix(true);
  18774. }
  18775. this.computeWorldMatrix(true);
  18776. this.getWorldMatrix().decompose(scale, rotation, position);
  18777. if (this.rotationQuaternion) {
  18778. this.rotationQuaternion.copyFrom(rotation);
  18779. }
  18780. else {
  18781. rotation.toEulerAnglesToRef(this.rotation);
  18782. }
  18783. this.scaling.x = scale.x;
  18784. this.scaling.y = scale.y;
  18785. this.scaling.z = scale.z;
  18786. this.position.x = position.x;
  18787. this.position.y = position.y;
  18788. this.position.z = position.z;
  18789. }
  18790. else {
  18791. var rotation = BABYLON.Tmp.Quaternion[0];
  18792. var position = BABYLON.Tmp.Vector3[0];
  18793. var scale = BABYLON.Tmp.Vector3[1];
  18794. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18795. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18796. this.computeWorldMatrix(true);
  18797. node.computeWorldMatrix(true);
  18798. node.getWorldMatrix().invertToRef(invParentMatrix);
  18799. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18800. diffMatrix.decompose(scale, rotation, position);
  18801. if (this.rotationQuaternion) {
  18802. this.rotationQuaternion.copyFrom(rotation);
  18803. }
  18804. else {
  18805. rotation.toEulerAnglesToRef(this.rotation);
  18806. }
  18807. this.position.x = position.x;
  18808. this.position.y = position.y;
  18809. this.position.z = position.z;
  18810. this.scaling.x = scale.x;
  18811. this.scaling.y = scale.y;
  18812. this.scaling.z = scale.z;
  18813. }
  18814. this.parent = node;
  18815. return this;
  18816. };
  18817. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18818. get: function () {
  18819. return this._nonUniformScaling;
  18820. },
  18821. enumerable: true,
  18822. configurable: true
  18823. });
  18824. /** @hidden */
  18825. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18826. if (this._nonUniformScaling === value) {
  18827. return false;
  18828. }
  18829. this._nonUniformScaling = value;
  18830. return true;
  18831. };
  18832. /**
  18833. * Attach the current TransformNode to another TransformNode associated with a bone
  18834. * @param bone Bone affecting the TransformNode
  18835. * @param affectedTransformNode TransformNode associated with the bone
  18836. */
  18837. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18838. this._transformToBoneReferal = affectedTransformNode;
  18839. this.parent = bone;
  18840. if (bone.getWorldMatrix().determinant() < 0) {
  18841. this.scalingDeterminant *= -1;
  18842. }
  18843. return this;
  18844. };
  18845. TransformNode.prototype.detachFromBone = function () {
  18846. if (!this.parent) {
  18847. return this;
  18848. }
  18849. if (this.parent.getWorldMatrix().determinant() < 0) {
  18850. this.scalingDeterminant *= -1;
  18851. }
  18852. this._transformToBoneReferal = null;
  18853. this.parent = null;
  18854. return this;
  18855. };
  18856. /**
  18857. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18858. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18859. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18860. * The passed axis is also normalized.
  18861. * Returns the TransformNode.
  18862. */
  18863. TransformNode.prototype.rotate = function (axis, amount, space) {
  18864. axis.normalize();
  18865. if (!this.rotationQuaternion) {
  18866. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18867. this.rotation = BABYLON.Vector3.Zero();
  18868. }
  18869. var rotationQuaternion;
  18870. if (!space || space === BABYLON.Space.LOCAL) {
  18871. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18872. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18873. }
  18874. else {
  18875. if (this.parent) {
  18876. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18877. invertParentWorldMatrix.invert();
  18878. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18879. }
  18880. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18881. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18882. }
  18883. return this;
  18884. };
  18885. /**
  18886. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18887. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18888. * The passed axis is also normalized.
  18889. * Returns the TransformNode.
  18890. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18891. */
  18892. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18893. axis.normalize();
  18894. if (!this.rotationQuaternion) {
  18895. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18896. this.rotation.copyFromFloats(0, 0, 0);
  18897. }
  18898. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18899. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18900. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18901. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18902. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18903. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18904. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18905. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18906. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18907. return this;
  18908. };
  18909. /**
  18910. * Translates the mesh along the axis vector for the passed distance in the given space.
  18911. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18912. * Returns the TransformNode.
  18913. */
  18914. TransformNode.prototype.translate = function (axis, distance, space) {
  18915. var displacementVector = axis.scale(distance);
  18916. if (!space || space === BABYLON.Space.LOCAL) {
  18917. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18918. this.setPositionWithLocalVector(tempV3);
  18919. }
  18920. else {
  18921. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18922. }
  18923. return this;
  18924. };
  18925. /**
  18926. * Adds a rotation step to the mesh current rotation.
  18927. * x, y, z are Euler angles expressed in radians.
  18928. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18929. * This means this rotation is made in the mesh local space only.
  18930. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18931. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18932. * ```javascript
  18933. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18934. * ```
  18935. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18936. * 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.
  18937. * Returns the TransformNode.
  18938. */
  18939. TransformNode.prototype.addRotation = function (x, y, z) {
  18940. var rotationQuaternion;
  18941. if (this.rotationQuaternion) {
  18942. rotationQuaternion = this.rotationQuaternion;
  18943. }
  18944. else {
  18945. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18946. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18947. }
  18948. var accumulation = BABYLON.Tmp.Quaternion[0];
  18949. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18950. rotationQuaternion.multiplyInPlace(accumulation);
  18951. if (!this.rotationQuaternion) {
  18952. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18953. }
  18954. return this;
  18955. };
  18956. /**
  18957. * Computes the mesh World matrix and returns it.
  18958. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18959. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18960. * If the parameter `force`is set to `true`, the actual computation is done.
  18961. * Returns the mesh World Matrix.
  18962. */
  18963. TransformNode.prototype.computeWorldMatrix = function (force) {
  18964. if (this._isWorldMatrixFrozen) {
  18965. return this._worldMatrix;
  18966. }
  18967. if (!force && this.isSynchronized(true)) {
  18968. this._currentRenderId = this.getScene().getRenderId();
  18969. return this._worldMatrix;
  18970. }
  18971. this._cache.position.copyFrom(this.position);
  18972. this._cache.scaling.copyFrom(this.scaling);
  18973. this._cache.pivotMatrixUpdated = false;
  18974. this._cache.billboardMode = this.billboardMode;
  18975. this._currentRenderId = this.getScene().getRenderId();
  18976. this._childRenderId = this.getScene().getRenderId();
  18977. this._isDirty = false;
  18978. // Scaling
  18979. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18980. // Rotation
  18981. //rotate, if quaternion is set and rotation was used
  18982. if (this.rotationQuaternion) {
  18983. var len = this.rotation.length();
  18984. if (len) {
  18985. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18986. this.rotation.copyFromFloats(0, 0, 0);
  18987. }
  18988. }
  18989. if (this.rotationQuaternion) {
  18990. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18991. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18992. }
  18993. else {
  18994. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18995. this._cache.rotation.copyFrom(this.rotation);
  18996. }
  18997. // Translation
  18998. var camera = this.getScene().activeCamera;
  18999. if (this.infiniteDistance && !this.parent && camera) {
  19000. var cameraWorldMatrix = camera.getWorldMatrix();
  19001. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19002. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19003. }
  19004. else {
  19005. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19006. }
  19007. // Composing transformations
  19008. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19009. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19010. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19011. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19012. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19013. // Need to decompose each rotation here
  19014. var currentPosition = BABYLON.Tmp.Vector3[3];
  19015. if (this.parent && this.parent.getWorldMatrix) {
  19016. if (this._transformToBoneReferal) {
  19017. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19018. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19019. }
  19020. else {
  19021. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19022. }
  19023. }
  19024. else {
  19025. currentPosition.copyFrom(this.position);
  19026. }
  19027. currentPosition.subtractInPlace(camera.globalPosition);
  19028. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19029. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19030. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19031. }
  19032. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19033. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19034. }
  19035. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19036. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19037. }
  19038. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19039. }
  19040. else {
  19041. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19042. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19043. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19044. }
  19045. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19046. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19047. }
  19048. // Post multiply inverse of pivotMatrix
  19049. if (this._postMultiplyPivotMatrix) {
  19050. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19051. }
  19052. // Local world
  19053. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19054. // Parent
  19055. if (this.parent && this.parent.getWorldMatrix) {
  19056. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19057. if (this._transformToBoneReferal) {
  19058. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19059. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19060. }
  19061. else {
  19062. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19063. }
  19064. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19065. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19066. this._worldMatrix.copyFrom(this._localWorld);
  19067. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19068. }
  19069. else {
  19070. if (this._transformToBoneReferal) {
  19071. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19072. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19073. }
  19074. else {
  19075. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19076. }
  19077. }
  19078. this._markSyncedWithParent();
  19079. }
  19080. else {
  19081. this._worldMatrix.copyFrom(this._localWorld);
  19082. }
  19083. // Normal matrix
  19084. if (!this.ignoreNonUniformScaling) {
  19085. if (this.scaling.isNonUniform) {
  19086. this._updateNonUniformScalingState(true);
  19087. }
  19088. else if (this.parent && this.parent._nonUniformScaling) {
  19089. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19090. }
  19091. else {
  19092. this._updateNonUniformScalingState(false);
  19093. }
  19094. }
  19095. else {
  19096. this._updateNonUniformScalingState(false);
  19097. }
  19098. this._afterComputeWorldMatrix();
  19099. // Absolute position
  19100. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19101. // Callbacks
  19102. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19103. if (!this._poseMatrix) {
  19104. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19105. }
  19106. // Cache the determinant
  19107. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19108. return this._worldMatrix;
  19109. };
  19110. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19111. };
  19112. /**
  19113. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19114. * @param func: callback function to add
  19115. *
  19116. * Returns the TransformNode.
  19117. */
  19118. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19119. this.onAfterWorldMatrixUpdateObservable.add(func);
  19120. return this;
  19121. };
  19122. /**
  19123. * Removes a registered callback function.
  19124. * Returns the TransformNode.
  19125. */
  19126. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19127. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19128. return this;
  19129. };
  19130. /**
  19131. * Clone the current transform node
  19132. * Returns the new transform node
  19133. * @param name Name of the new clone
  19134. * @param newParent New parent for the clone
  19135. * @param doNotCloneChildren Do not clone children hierarchy
  19136. */
  19137. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19138. var _this = this;
  19139. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19140. result.name = name;
  19141. result.id = name;
  19142. if (newParent) {
  19143. result.parent = newParent;
  19144. }
  19145. if (!doNotCloneChildren) {
  19146. // Children
  19147. var directDescendants = this.getDescendants(true);
  19148. for (var index = 0; index < directDescendants.length; index++) {
  19149. var child = directDescendants[index];
  19150. if (child.clone) {
  19151. child.clone(name + "." + child.name, result);
  19152. }
  19153. }
  19154. }
  19155. return result;
  19156. };
  19157. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19158. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19159. serializationObject.type = this.getClassName();
  19160. // Parent
  19161. if (this.parent) {
  19162. serializationObject.parentId = this.parent.id;
  19163. }
  19164. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19165. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19166. }
  19167. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19168. serializationObject.isEnabled = this.isEnabled();
  19169. // Parent
  19170. if (this.parent) {
  19171. serializationObject.parentId = this.parent.id;
  19172. }
  19173. return serializationObject;
  19174. };
  19175. // Statics
  19176. /**
  19177. * Returns a new TransformNode object parsed from the source provided.
  19178. * The parameter `parsedMesh` is the source.
  19179. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19180. */
  19181. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19182. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19183. if (BABYLON.Tags) {
  19184. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19185. }
  19186. if (parsedTransformNode.localMatrix) {
  19187. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19188. }
  19189. else if (parsedTransformNode.pivotMatrix) {
  19190. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19191. }
  19192. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19193. // Parent
  19194. if (parsedTransformNode.parentId) {
  19195. transformNode._waitingParentId = parsedTransformNode.parentId;
  19196. }
  19197. return transformNode;
  19198. };
  19199. /**
  19200. * Releases resources associated with this transform node.
  19201. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19202. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19203. */
  19204. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19205. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19206. // Animations
  19207. this.getScene().stopAnimation(this);
  19208. // Remove from scene
  19209. this.getScene().removeTransformNode(this);
  19210. this.onAfterWorldMatrixUpdateObservable.clear();
  19211. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19212. };
  19213. // Statics
  19214. TransformNode.BILLBOARDMODE_NONE = 0;
  19215. TransformNode.BILLBOARDMODE_X = 1;
  19216. TransformNode.BILLBOARDMODE_Y = 2;
  19217. TransformNode.BILLBOARDMODE_Z = 4;
  19218. TransformNode.BILLBOARDMODE_ALL = 7;
  19219. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19220. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19221. __decorate([
  19222. BABYLON.serializeAsVector3()
  19223. ], TransformNode.prototype, "_rotation", void 0);
  19224. __decorate([
  19225. BABYLON.serializeAsQuaternion()
  19226. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19227. __decorate([
  19228. BABYLON.serializeAsVector3()
  19229. ], TransformNode.prototype, "_scaling", void 0);
  19230. __decorate([
  19231. BABYLON.serialize()
  19232. ], TransformNode.prototype, "billboardMode", void 0);
  19233. __decorate([
  19234. BABYLON.serialize()
  19235. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19236. __decorate([
  19237. BABYLON.serialize()
  19238. ], TransformNode.prototype, "infiniteDistance", void 0);
  19239. __decorate([
  19240. BABYLON.serialize()
  19241. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19242. __decorate([
  19243. BABYLON.serializeAsVector3()
  19244. ], TransformNode.prototype, "position", void 0);
  19245. return TransformNode;
  19246. }(BABYLON.Node));
  19247. BABYLON.TransformNode = TransformNode;
  19248. })(BABYLON || (BABYLON = {}));
  19249. //# sourceMappingURL=babylon.transformNode.js.map
  19250. var BABYLON;
  19251. (function (BABYLON) {
  19252. /**
  19253. * Class used to store all common mesh properties
  19254. */
  19255. var AbstractMesh = /** @class */ (function (_super) {
  19256. __extends(AbstractMesh, _super);
  19257. // Constructor
  19258. /**
  19259. * Creates a new AbstractMesh
  19260. * @param name defines the name of the mesh
  19261. * @param scene defines the hosting scene
  19262. */
  19263. function AbstractMesh(name, scene) {
  19264. if (scene === void 0) { scene = null; }
  19265. var _this = _super.call(this, name, scene, false) || this;
  19266. _this._facetNb = 0; // facet number
  19267. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19268. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19269. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19270. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19271. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19272. _this._subDiv = {
  19273. max: 1,
  19274. X: 1,
  19275. Y: 1,
  19276. Z: 1
  19277. };
  19278. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19279. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19280. // Events
  19281. /**
  19282. * An event triggered when this mesh collides with another one
  19283. */
  19284. _this.onCollideObservable = new BABYLON.Observable();
  19285. /**
  19286. * An event triggered when the collision's position changes
  19287. */
  19288. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19289. /**
  19290. * An event triggered when material is changed
  19291. */
  19292. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19293. // Properties
  19294. /**
  19295. * Gets or sets the orientation for POV movement & rotation
  19296. */
  19297. _this.definedFacingForward = true;
  19298. /**
  19299. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19300. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19301. * * 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.
  19302. * @see http://doc.babylonjs.com/features/occlusionquery
  19303. */
  19304. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19305. /**
  19306. * 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:
  19307. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19308. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19309. * * 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.
  19310. * @see http://doc.babylonjs.com/features/occlusionquery
  19311. */
  19312. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19313. /**
  19314. * 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.
  19315. * The default value is -1 which means don't break the query and wait till the result
  19316. * @see http://doc.babylonjs.com/features/occlusionquery
  19317. */
  19318. _this.occlusionRetryCount = -1;
  19319. /** @hidden */
  19320. _this._occlusionInternalRetryCounter = 0;
  19321. /** @hidden */
  19322. _this._isOccluded = false;
  19323. /** @hidden */
  19324. _this._isOcclusionQueryInProgress = false;
  19325. _this._visibility = 1.0;
  19326. /** Gets or sets the alpha index used to sort transparent meshes
  19327. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19328. */
  19329. _this.alphaIndex = Number.MAX_VALUE;
  19330. /**
  19331. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19332. */
  19333. _this.isVisible = true;
  19334. /**
  19335. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19336. */
  19337. _this.isPickable = true;
  19338. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19339. _this.showSubMeshesBoundingBox = false;
  19340. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19341. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19342. */
  19343. _this.isBlocker = false;
  19344. /**
  19345. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19346. */
  19347. _this.enablePointerMoveEvents = false;
  19348. /**
  19349. * Specifies the rendering group id for this mesh (0 by default)
  19350. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19351. */
  19352. _this.renderingGroupId = 0;
  19353. _this._receiveShadows = false;
  19354. /**
  19355. * Gets or sets a boolean indicating if the outline must be rendered as well
  19356. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19357. */
  19358. _this.renderOutline = false;
  19359. /** Defines color to use when rendering outline */
  19360. _this.outlineColor = BABYLON.Color3.Red();
  19361. /** Define width to use when rendering outline */
  19362. _this.outlineWidth = 0.02;
  19363. /**
  19364. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19365. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19366. */
  19367. _this.renderOverlay = false;
  19368. /** Defines color to use when rendering overlay */
  19369. _this.overlayColor = BABYLON.Color3.Red();
  19370. /** Defines alpha to use when rendering overlay */
  19371. _this.overlayAlpha = 0.5;
  19372. _this._hasVertexAlpha = false;
  19373. _this._useVertexColors = true;
  19374. _this._computeBonesUsingShaders = true;
  19375. _this._numBoneInfluencers = 4;
  19376. _this._applyFog = true;
  19377. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19378. _this.useOctreeForRenderingSelection = true;
  19379. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19380. _this.useOctreeForPicking = true;
  19381. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19382. _this.useOctreeForCollisions = true;
  19383. _this._layerMask = 0x0FFFFFFF;
  19384. /**
  19385. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19386. */
  19387. _this.alwaysSelectAsActiveMesh = false;
  19388. /**
  19389. * Gets or sets the current action manager
  19390. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19391. */
  19392. _this.actionManager = null;
  19393. /**
  19394. * Gets or sets impostor used for physic simulation
  19395. * @see http://doc.babylonjs.com/features/physics_engine
  19396. */
  19397. _this.physicsImpostor = null;
  19398. // Collisions
  19399. _this._checkCollisions = false;
  19400. _this._collisionMask = -1;
  19401. _this._collisionGroup = -1;
  19402. /**
  19403. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19404. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19405. */
  19406. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19407. /**
  19408. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19409. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19410. */
  19411. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19412. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19413. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19414. // Edges
  19415. /**
  19416. * Defines edge width used when edgesRenderer is enabled
  19417. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19418. */
  19419. _this.edgesWidth = 1;
  19420. /**
  19421. * Defines edge color used when edgesRenderer is enabled
  19422. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19423. */
  19424. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19425. // Cache
  19426. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19427. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19428. /** @hidden */
  19429. _this._renderId = 0;
  19430. /** @hidden */
  19431. _this._intersectionsInProgress = new Array();
  19432. /** @hidden */
  19433. _this._unIndexed = false;
  19434. /** @hidden */
  19435. _this._lightSources = new Array();
  19436. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19437. if (collidedMesh === void 0) { collidedMesh = null; }
  19438. //TODO move this to the collision coordinator!
  19439. if (_this.getScene().workerCollisions)
  19440. newPosition.multiplyInPlace(_this._collider._radius);
  19441. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19442. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19443. _this.position.addInPlace(_this._diffPositionForCollisions);
  19444. }
  19445. if (collidedMesh) {
  19446. _this.onCollideObservable.notifyObservers(collidedMesh);
  19447. }
  19448. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19449. };
  19450. _this.getScene().addMesh(_this);
  19451. _this._resyncLightSources();
  19452. return _this;
  19453. }
  19454. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19455. /**
  19456. * No billboard
  19457. */
  19458. get: function () {
  19459. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19460. },
  19461. enumerable: true,
  19462. configurable: true
  19463. });
  19464. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19465. /** Billboard on X axis */
  19466. get: function () {
  19467. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19468. },
  19469. enumerable: true,
  19470. configurable: true
  19471. });
  19472. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19473. /** Billboard on Y axis */
  19474. get: function () {
  19475. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19476. },
  19477. enumerable: true,
  19478. configurable: true
  19479. });
  19480. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19481. /** Billboard on Z axis */
  19482. get: function () {
  19483. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19489. /** Billboard on all axes */
  19490. get: function () {
  19491. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19497. /**
  19498. * Gets the number of facets in the mesh
  19499. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19500. */
  19501. get: function () {
  19502. return this._facetNb;
  19503. },
  19504. enumerable: true,
  19505. configurable: true
  19506. });
  19507. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19508. /**
  19509. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19510. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19511. */
  19512. get: function () {
  19513. return this._partitioningSubdivisions;
  19514. },
  19515. set: function (nb) {
  19516. this._partitioningSubdivisions = nb;
  19517. },
  19518. enumerable: true,
  19519. configurable: true
  19520. });
  19521. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19522. /**
  19523. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19524. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19525. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19526. */
  19527. get: function () {
  19528. return this._partitioningBBoxRatio;
  19529. },
  19530. set: function (ratio) {
  19531. this._partitioningBBoxRatio = ratio;
  19532. },
  19533. enumerable: true,
  19534. configurable: true
  19535. });
  19536. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19537. /**
  19538. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19539. * Works only for updatable meshes.
  19540. * Doesn't work with multi-materials
  19541. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19542. */
  19543. get: function () {
  19544. return this._facetDepthSort;
  19545. },
  19546. set: function (sort) {
  19547. this._facetDepthSort = sort;
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19553. /**
  19554. * The location (Vector3) where the facet depth sort must be computed from.
  19555. * By default, the active camera position.
  19556. * Used only when facet depth sort is enabled
  19557. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19558. */
  19559. get: function () {
  19560. return this._facetDepthSortFrom;
  19561. },
  19562. set: function (location) {
  19563. this._facetDepthSortFrom = location;
  19564. },
  19565. enumerable: true,
  19566. configurable: true
  19567. });
  19568. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19569. /**
  19570. * gets a boolean indicating if facetData is enabled
  19571. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19572. */
  19573. get: function () {
  19574. return this._facetDataEnabled;
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. /** @hidden */
  19580. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19581. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19582. return false;
  19583. }
  19584. this._markSubMeshesAsMiscDirty();
  19585. return true;
  19586. };
  19587. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19588. /** Set a function to call when this mesh collides with another one */
  19589. set: function (callback) {
  19590. if (this._onCollideObserver) {
  19591. this.onCollideObservable.remove(this._onCollideObserver);
  19592. }
  19593. this._onCollideObserver = this.onCollideObservable.add(callback);
  19594. },
  19595. enumerable: true,
  19596. configurable: true
  19597. });
  19598. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19599. /** Set a function to call when the collision's position changes */
  19600. set: function (callback) {
  19601. if (this._onCollisionPositionChangeObserver) {
  19602. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19603. }
  19604. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19605. },
  19606. enumerable: true,
  19607. configurable: true
  19608. });
  19609. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19610. /**
  19611. * 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
  19612. * @see http://doc.babylonjs.com/features/occlusionquery
  19613. */
  19614. get: function () {
  19615. return this._isOccluded;
  19616. },
  19617. set: function (value) {
  19618. this._isOccluded = value;
  19619. },
  19620. enumerable: true,
  19621. configurable: true
  19622. });
  19623. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19624. /**
  19625. * Flag to check the progress status of the query
  19626. * @see http://doc.babylonjs.com/features/occlusionquery
  19627. */
  19628. get: function () {
  19629. return this._isOcclusionQueryInProgress;
  19630. },
  19631. enumerable: true,
  19632. configurable: true
  19633. });
  19634. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19635. /**
  19636. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19637. */
  19638. get: function () {
  19639. return this._visibility;
  19640. },
  19641. /**
  19642. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19643. */
  19644. set: function (value) {
  19645. if (this._visibility === value) {
  19646. return;
  19647. }
  19648. this._visibility = value;
  19649. this._markSubMeshesAsMiscDirty();
  19650. },
  19651. enumerable: true,
  19652. configurable: true
  19653. });
  19654. Object.defineProperty(AbstractMesh.prototype, "material", {
  19655. /** Gets or sets current material */
  19656. get: function () {
  19657. return this._material;
  19658. },
  19659. set: function (value) {
  19660. if (this._material === value) {
  19661. return;
  19662. }
  19663. this._material = value;
  19664. if (this.onMaterialChangedObservable.hasObservers) {
  19665. this.onMaterialChangedObservable.notifyObservers(this);
  19666. }
  19667. if (!this.subMeshes) {
  19668. return;
  19669. }
  19670. this._unBindEffect();
  19671. },
  19672. enumerable: true,
  19673. configurable: true
  19674. });
  19675. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19676. /**
  19677. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19678. * @see http://doc.babylonjs.com/babylon101/shadows
  19679. */
  19680. get: function () {
  19681. return this._receiveShadows;
  19682. },
  19683. set: function (value) {
  19684. if (this._receiveShadows === value) {
  19685. return;
  19686. }
  19687. this._receiveShadows = value;
  19688. this._markSubMeshesAsLightDirty();
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19694. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19695. get: function () {
  19696. return this._hasVertexAlpha;
  19697. },
  19698. set: function (value) {
  19699. if (this._hasVertexAlpha === value) {
  19700. return;
  19701. }
  19702. this._hasVertexAlpha = value;
  19703. this._markSubMeshesAsAttributesDirty();
  19704. this._markSubMeshesAsMiscDirty();
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19710. /** 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) */
  19711. get: function () {
  19712. return this._useVertexColors;
  19713. },
  19714. set: function (value) {
  19715. if (this._useVertexColors === value) {
  19716. return;
  19717. }
  19718. this._useVertexColors = value;
  19719. this._markSubMeshesAsAttributesDirty();
  19720. },
  19721. enumerable: true,
  19722. configurable: true
  19723. });
  19724. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19725. /**
  19726. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19727. */
  19728. get: function () {
  19729. return this._computeBonesUsingShaders;
  19730. },
  19731. set: function (value) {
  19732. if (this._computeBonesUsingShaders === value) {
  19733. return;
  19734. }
  19735. this._computeBonesUsingShaders = value;
  19736. this._markSubMeshesAsAttributesDirty();
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19742. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19743. get: function () {
  19744. return this._numBoneInfluencers;
  19745. },
  19746. set: function (value) {
  19747. if (this._numBoneInfluencers === value) {
  19748. return;
  19749. }
  19750. this._numBoneInfluencers = value;
  19751. this._markSubMeshesAsAttributesDirty();
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19757. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19758. get: function () {
  19759. return this._applyFog;
  19760. },
  19761. set: function (value) {
  19762. if (this._applyFog === value) {
  19763. return;
  19764. }
  19765. this._applyFog = value;
  19766. this._markSubMeshesAsMiscDirty();
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19772. /**
  19773. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19774. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19775. */
  19776. get: function () {
  19777. return this._layerMask;
  19778. },
  19779. set: function (value) {
  19780. if (value === this._layerMask) {
  19781. return;
  19782. }
  19783. this._layerMask = value;
  19784. this._resyncLightSources();
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19790. /**
  19791. * Gets or sets a collision mask used to mask collisions (default is -1).
  19792. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19793. */
  19794. get: function () {
  19795. return this._collisionMask;
  19796. },
  19797. set: function (mask) {
  19798. this._collisionMask = !isNaN(mask) ? mask : -1;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19804. /**
  19805. * Gets or sets the current collision group mask (-1 by default).
  19806. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19807. */
  19808. get: function () {
  19809. return this._collisionGroup;
  19810. },
  19811. set: function (mask) {
  19812. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19813. },
  19814. enumerable: true,
  19815. configurable: true
  19816. });
  19817. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19818. /** @hidden */
  19819. get: function () {
  19820. return null;
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19826. get: function () {
  19827. return this._skeleton;
  19828. },
  19829. /**
  19830. * Gets or sets a skeleton to apply skining transformations
  19831. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19832. */
  19833. set: function (value) {
  19834. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19835. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19836. }
  19837. if (value && value.needInitialSkinMatrix) {
  19838. value._registerMeshWithPoseMatrix(this);
  19839. }
  19840. this._skeleton = value;
  19841. if (!this._skeleton) {
  19842. this._bonesTransformMatrices = null;
  19843. }
  19844. this._markSubMeshesAsAttributesDirty();
  19845. },
  19846. enumerable: true,
  19847. configurable: true
  19848. });
  19849. /**
  19850. * Returns the string "AbstractMesh"
  19851. * @returns "AbstractMesh"
  19852. */
  19853. AbstractMesh.prototype.getClassName = function () {
  19854. return "AbstractMesh";
  19855. };
  19856. /**
  19857. * Gets a string representation of the current mesh
  19858. * @param fullDetails defines a boolean indicating if full details must be included
  19859. * @returns a string representation of the current mesh
  19860. */
  19861. AbstractMesh.prototype.toString = function (fullDetails) {
  19862. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19863. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19864. if (this._skeleton) {
  19865. ret += ", skeleton: " + this._skeleton.name;
  19866. }
  19867. if (fullDetails) {
  19868. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19869. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19870. }
  19871. return ret;
  19872. };
  19873. /** @hidden */
  19874. AbstractMesh.prototype._rebuild = function () {
  19875. if (this._occlusionQuery) {
  19876. this._occlusionQuery = null;
  19877. }
  19878. if (this._edgesRenderer) {
  19879. this._edgesRenderer._rebuild();
  19880. }
  19881. if (!this.subMeshes) {
  19882. return;
  19883. }
  19884. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19885. var subMesh = _a[_i];
  19886. subMesh._rebuild();
  19887. }
  19888. };
  19889. /** @hidden */
  19890. AbstractMesh.prototype._resyncLightSources = function () {
  19891. this._lightSources.length = 0;
  19892. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19893. var light = _a[_i];
  19894. if (!light.isEnabled()) {
  19895. continue;
  19896. }
  19897. if (light.canAffectMesh(this)) {
  19898. this._lightSources.push(light);
  19899. }
  19900. }
  19901. this._markSubMeshesAsLightDirty();
  19902. };
  19903. /** @hidden */
  19904. AbstractMesh.prototype._resyncLighSource = function (light) {
  19905. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19906. var index = this._lightSources.indexOf(light);
  19907. if (index === -1) {
  19908. if (!isIn) {
  19909. return;
  19910. }
  19911. this._lightSources.push(light);
  19912. }
  19913. else {
  19914. if (isIn) {
  19915. return;
  19916. }
  19917. this._lightSources.splice(index, 1);
  19918. }
  19919. this._markSubMeshesAsLightDirty();
  19920. };
  19921. /** @hidden */
  19922. AbstractMesh.prototype._unBindEffect = function () {
  19923. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19924. var subMesh = _a[_i];
  19925. subMesh.setEffect(null);
  19926. }
  19927. };
  19928. /** @hidden */
  19929. AbstractMesh.prototype._removeLightSource = function (light) {
  19930. var index = this._lightSources.indexOf(light);
  19931. if (index === -1) {
  19932. return;
  19933. }
  19934. this._lightSources.splice(index, 1);
  19935. this._markSubMeshesAsLightDirty();
  19936. };
  19937. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19938. if (!this.subMeshes) {
  19939. return;
  19940. }
  19941. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19942. var subMesh = _a[_i];
  19943. if (subMesh._materialDefines) {
  19944. func(subMesh._materialDefines);
  19945. }
  19946. }
  19947. };
  19948. /** @hidden */
  19949. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19950. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19951. };
  19952. /** @hidden */
  19953. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19954. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19955. };
  19956. /** @hidden */
  19957. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19958. if (!this.subMeshes) {
  19959. return;
  19960. }
  19961. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19962. var subMesh = _a[_i];
  19963. var material = subMesh.getMaterial();
  19964. if (material) {
  19965. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19966. }
  19967. }
  19968. };
  19969. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19970. /**
  19971. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19972. */
  19973. get: function () {
  19974. return this._scaling;
  19975. },
  19976. set: function (newScaling) {
  19977. this._scaling = newScaling;
  19978. if (this.physicsImpostor) {
  19979. this.physicsImpostor.forceUpdate();
  19980. }
  19981. },
  19982. enumerable: true,
  19983. configurable: true
  19984. });
  19985. // Methods
  19986. /**
  19987. * Disables the mesh edge rendering mode
  19988. * @returns the currentAbstractMesh
  19989. */
  19990. AbstractMesh.prototype.disableEdgesRendering = function () {
  19991. if (this._edgesRenderer) {
  19992. this._edgesRenderer.dispose();
  19993. this._edgesRenderer = null;
  19994. }
  19995. return this;
  19996. };
  19997. /**
  19998. * Enables the edge rendering mode on the mesh.
  19999. * This mode makes the mesh edges visible
  20000. * @param epsilon defines the maximal distance between two angles to detect a face
  20001. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20002. * @returns the currentAbstractMesh
  20003. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20004. */
  20005. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20006. if (epsilon === void 0) { epsilon = 0.95; }
  20007. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20008. this.disableEdgesRendering();
  20009. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20010. return this;
  20011. };
  20012. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20013. /**
  20014. * Gets the edgesRenderer associated with the mesh
  20015. */
  20016. get: function () {
  20017. return this._edgesRenderer;
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20023. /**
  20024. * Returns true if the mesh is blocked. Implemented by child classes
  20025. */
  20026. get: function () {
  20027. return false;
  20028. },
  20029. enumerable: true,
  20030. configurable: true
  20031. });
  20032. /**
  20033. * Returns the mesh itself by default. Implemented by child classes
  20034. * @param camera defines the camera to use to pick the right LOD level
  20035. * @returns the currentAbstractMesh
  20036. */
  20037. AbstractMesh.prototype.getLOD = function (camera) {
  20038. return this;
  20039. };
  20040. /**
  20041. * Returns 0 by default. Implemented by child classes
  20042. * @returns an integer
  20043. */
  20044. AbstractMesh.prototype.getTotalVertices = function () {
  20045. return 0;
  20046. };
  20047. /**
  20048. * Returns null by default. Implemented by child classes
  20049. * @returns null
  20050. */
  20051. AbstractMesh.prototype.getIndices = function () {
  20052. return null;
  20053. };
  20054. /**
  20055. * Returns the array of the requested vertex data kind. Implemented by child classes
  20056. * @param kind defines the vertex data kind to use
  20057. * @returns null
  20058. */
  20059. AbstractMesh.prototype.getVerticesData = function (kind) {
  20060. return null;
  20061. };
  20062. /**
  20063. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20064. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20065. * Note that a new underlying VertexBuffer object is created each call.
  20066. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20067. * @param kind defines vertex data kind:
  20068. * * BABYLON.VertexBuffer.PositionKind
  20069. * * BABYLON.VertexBuffer.UVKind
  20070. * * BABYLON.VertexBuffer.UV2Kind
  20071. * * BABYLON.VertexBuffer.UV3Kind
  20072. * * BABYLON.VertexBuffer.UV4Kind
  20073. * * BABYLON.VertexBuffer.UV5Kind
  20074. * * BABYLON.VertexBuffer.UV6Kind
  20075. * * BABYLON.VertexBuffer.ColorKind
  20076. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20077. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20078. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20079. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20080. * @param data defines the data source
  20081. * @param updatable defines if the data must be flagged as updatable (or static)
  20082. * @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
  20083. * @returns the current mesh
  20084. */
  20085. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20086. return this;
  20087. };
  20088. /**
  20089. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20090. * If the mesh has no geometry, it is simply returned as it is.
  20091. * @param kind defines vertex data kind:
  20092. * * BABYLON.VertexBuffer.PositionKind
  20093. * * BABYLON.VertexBuffer.UVKind
  20094. * * BABYLON.VertexBuffer.UV2Kind
  20095. * * BABYLON.VertexBuffer.UV3Kind
  20096. * * BABYLON.VertexBuffer.UV4Kind
  20097. * * BABYLON.VertexBuffer.UV5Kind
  20098. * * BABYLON.VertexBuffer.UV6Kind
  20099. * * BABYLON.VertexBuffer.ColorKind
  20100. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20101. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20102. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20103. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20104. * @param data defines the data source
  20105. * @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
  20106. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20107. * @returns the current mesh
  20108. */
  20109. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20110. return this;
  20111. };
  20112. /**
  20113. * Sets the mesh indices,
  20114. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20115. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20116. * @param totalVertices Defines the total number of vertices
  20117. * @returns the current mesh
  20118. */
  20119. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20120. return this;
  20121. };
  20122. /**
  20123. * Gets a boolean indicating if specific vertex data is present
  20124. * @param kind defines the vertex data kind to use
  20125. * @returns true is data kind is present
  20126. */
  20127. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20128. return false;
  20129. };
  20130. /**
  20131. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20132. * @returns a BoundingInfo
  20133. */
  20134. AbstractMesh.prototype.getBoundingInfo = function () {
  20135. if (this._masterMesh) {
  20136. return this._masterMesh.getBoundingInfo();
  20137. }
  20138. if (!this._boundingInfo) {
  20139. // this._boundingInfo is being created here
  20140. this._updateBoundingInfo();
  20141. }
  20142. // cannot be null.
  20143. return this._boundingInfo;
  20144. };
  20145. /**
  20146. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20147. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20148. * @returns the current mesh
  20149. */
  20150. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20151. if (includeDescendants === void 0) { includeDescendants = true; }
  20152. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20153. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20154. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20155. if (maxDimension === 0) {
  20156. return this;
  20157. }
  20158. var scale = 1 / maxDimension;
  20159. this.scaling.scaleInPlace(scale);
  20160. return this;
  20161. };
  20162. /**
  20163. * Overwrite the current bounding info
  20164. * @param boundingInfo defines the new bounding info
  20165. * @returns the current mesh
  20166. */
  20167. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20168. this._boundingInfo = boundingInfo;
  20169. return this;
  20170. };
  20171. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20172. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20173. get: function () {
  20174. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20175. },
  20176. enumerable: true,
  20177. configurable: true
  20178. });
  20179. /** @hidden */
  20180. AbstractMesh.prototype._preActivate = function () {
  20181. };
  20182. /** @hidden */
  20183. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20184. };
  20185. /** @hidden */
  20186. AbstractMesh.prototype._activate = function (renderId) {
  20187. this._renderId = renderId;
  20188. };
  20189. /**
  20190. * Gets the current world matrix
  20191. * @returns a Matrix
  20192. */
  20193. AbstractMesh.prototype.getWorldMatrix = function () {
  20194. if (this._masterMesh) {
  20195. return this._masterMesh.getWorldMatrix();
  20196. }
  20197. return _super.prototype.getWorldMatrix.call(this);
  20198. };
  20199. /** @hidden */
  20200. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20201. if (this._masterMesh) {
  20202. return this._masterMesh._getWorldMatrixDeterminant();
  20203. }
  20204. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20205. };
  20206. // ================================== Point of View Movement =================================
  20207. /**
  20208. * Perform relative position change from the point of view of behind the front of the mesh.
  20209. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20210. * Supports definition of mesh facing forward or backward
  20211. * @param amountRight defines the distance on the right axis
  20212. * @param amountUp defines the distance on the up axis
  20213. * @param amountForward defines the distance on the forward axis
  20214. * @returns the current mesh
  20215. */
  20216. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20217. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20218. return this;
  20219. };
  20220. /**
  20221. * Calculate relative position change from the point of view of behind the front of the mesh.
  20222. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20223. * Supports definition of mesh facing forward or backward
  20224. * @param amountRight defines the distance on the right axis
  20225. * @param amountUp defines the distance on the up axis
  20226. * @param amountForward defines the distance on the forward axis
  20227. * @returns the new displacement vector
  20228. */
  20229. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20230. var rotMatrix = new BABYLON.Matrix();
  20231. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20232. rotQuaternion.toRotationMatrix(rotMatrix);
  20233. var translationDelta = BABYLON.Vector3.Zero();
  20234. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20235. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20236. return translationDelta;
  20237. };
  20238. // ================================== Point of View Rotation =================================
  20239. /**
  20240. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20241. * Supports definition of mesh facing forward or backward
  20242. * @param flipBack defines the flip
  20243. * @param twirlClockwise defines the twirl
  20244. * @param tiltRight defines the tilt
  20245. * @returns the current mesh
  20246. */
  20247. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20248. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20249. return this;
  20250. };
  20251. /**
  20252. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20253. * Supports definition of mesh facing forward or backward.
  20254. * @param flipBack defines the flip
  20255. * @param twirlClockwise defines the twirl
  20256. * @param tiltRight defines the tilt
  20257. * @returns the new rotation vector
  20258. */
  20259. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20260. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20261. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20262. };
  20263. /**
  20264. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20265. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20266. * @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
  20267. * @returns the new bounding vectors
  20268. */
  20269. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20270. if (includeDescendants === void 0) { includeDescendants = true; }
  20271. if (predicate === void 0) { predicate = null; }
  20272. // Ensures that all world matrix will be recomputed.
  20273. this.getScene().incrementRenderId();
  20274. this.computeWorldMatrix(true);
  20275. var min;
  20276. var max;
  20277. var boundingInfo = this.getBoundingInfo();
  20278. if (!this.subMeshes) {
  20279. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20280. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20281. }
  20282. else {
  20283. min = boundingInfo.boundingBox.minimumWorld;
  20284. max = boundingInfo.boundingBox.maximumWorld;
  20285. }
  20286. if (includeDescendants) {
  20287. var descendants = this.getDescendants(false);
  20288. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20289. var descendant = descendants_1[_i];
  20290. var childMesh = descendant;
  20291. childMesh.computeWorldMatrix(true);
  20292. // Filters meshes based on custom predicate function.
  20293. if (predicate && !predicate(childMesh)) {
  20294. continue;
  20295. }
  20296. //make sure we have the needed params to get mix and max
  20297. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20298. continue;
  20299. }
  20300. var childBoundingInfo = childMesh.getBoundingInfo();
  20301. var boundingBox = childBoundingInfo.boundingBox;
  20302. var minBox = boundingBox.minimumWorld;
  20303. var maxBox = boundingBox.maximumWorld;
  20304. BABYLON.Tools.CheckExtends(minBox, min, max);
  20305. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20306. }
  20307. }
  20308. return {
  20309. min: min,
  20310. max: max
  20311. };
  20312. };
  20313. /** @hidden */
  20314. AbstractMesh.prototype._updateBoundingInfo = function () {
  20315. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20316. this._boundingInfo.update(this.worldMatrixFromCache);
  20317. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20318. return this;
  20319. };
  20320. /** @hidden */
  20321. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20322. if (!this.subMeshes) {
  20323. return this;
  20324. }
  20325. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20326. var subMesh = this.subMeshes[subIndex];
  20327. if (!subMesh.IsGlobal) {
  20328. subMesh.updateBoundingInfo(matrix);
  20329. }
  20330. }
  20331. return this;
  20332. };
  20333. /** @hidden */
  20334. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20335. // Bounding info
  20336. this._updateBoundingInfo();
  20337. };
  20338. /**
  20339. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20340. * A mesh is in the frustum if its bounding box intersects the frustum
  20341. * @param frustumPlanes defines the frustum to test
  20342. * @returns true if the mesh is in the frustum planes
  20343. */
  20344. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20345. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20346. };
  20347. /**
  20348. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20349. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20350. * @param frustumPlanes defines the frustum to test
  20351. * @returns true if the mesh is completely in the frustum planes
  20352. */
  20353. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20354. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20355. };
  20356. /**
  20357. * True if the mesh intersects another mesh or a SolidParticle object
  20358. * @param mesh defines a target mesh or SolidParticle to test
  20359. * @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)
  20360. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20361. * @returns true if there is an intersection
  20362. */
  20363. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20364. if (precise === void 0) { precise = false; }
  20365. if (!this._boundingInfo || !mesh._boundingInfo) {
  20366. return false;
  20367. }
  20368. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20369. return true;
  20370. }
  20371. if (includeDescendants) {
  20372. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20373. var child = _a[_i];
  20374. if (child.intersectsMesh(mesh, precise, true)) {
  20375. return true;
  20376. }
  20377. }
  20378. }
  20379. return false;
  20380. };
  20381. /**
  20382. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20383. * @param point defines the point to test
  20384. * @returns true if there is an intersection
  20385. */
  20386. AbstractMesh.prototype.intersectsPoint = function (point) {
  20387. if (!this._boundingInfo) {
  20388. return false;
  20389. }
  20390. return this._boundingInfo.intersectsPoint(point);
  20391. };
  20392. /**
  20393. * Gets the current physics impostor
  20394. * @see http://doc.babylonjs.com/features/physics_engine
  20395. * @returns a physics impostor or null
  20396. */
  20397. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20398. return this.physicsImpostor;
  20399. };
  20400. /**
  20401. * Gets the position of the current mesh in camera space
  20402. * @param camera defines the camera to use
  20403. * @returns a position
  20404. */
  20405. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20406. if (camera === void 0) { camera = null; }
  20407. if (!camera) {
  20408. camera = this.getScene().activeCamera;
  20409. }
  20410. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20411. };
  20412. /**
  20413. * Returns the distance from the mesh to the active camera
  20414. * @param camera defines the camera to use
  20415. * @returns the distance
  20416. */
  20417. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20418. if (camera === void 0) { camera = null; }
  20419. if (!camera) {
  20420. camera = this.getScene().activeCamera;
  20421. }
  20422. return this.absolutePosition.subtract(camera.position).length();
  20423. };
  20424. /**
  20425. * Apply a physic impulse to the mesh
  20426. * @param force defines the force to apply
  20427. * @param contactPoint defines where to apply the force
  20428. * @returns the current mesh
  20429. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20430. */
  20431. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20432. if (!this.physicsImpostor) {
  20433. return this;
  20434. }
  20435. this.physicsImpostor.applyImpulse(force, contactPoint);
  20436. return this;
  20437. };
  20438. /**
  20439. * Creates a physic joint between two meshes
  20440. * @param otherMesh defines the other mesh to use
  20441. * @param pivot1 defines the pivot to use on this mesh
  20442. * @param pivot2 defines the pivot to use on the other mesh
  20443. * @param options defines additional options (can be plugin dependent)
  20444. * @returns the current mesh
  20445. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20446. */
  20447. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20448. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20449. return this;
  20450. }
  20451. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20452. mainPivot: pivot1,
  20453. connectedPivot: pivot2,
  20454. nativeParams: options
  20455. });
  20456. return this;
  20457. };
  20458. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20459. // Collisions
  20460. /**
  20461. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20462. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20463. */
  20464. get: function () {
  20465. return this._checkCollisions;
  20466. },
  20467. set: function (collisionEnabled) {
  20468. this._checkCollisions = collisionEnabled;
  20469. if (this.getScene().workerCollisions) {
  20470. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20471. }
  20472. },
  20473. enumerable: true,
  20474. configurable: true
  20475. });
  20476. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20477. /**
  20478. * Gets Collider object used to compute collisions (not physics)
  20479. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20480. */
  20481. get: function () {
  20482. return this._collider;
  20483. },
  20484. enumerable: true,
  20485. configurable: true
  20486. });
  20487. /**
  20488. * Move the mesh using collision engine
  20489. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20490. * @param displacement defines the requested displacement vector
  20491. * @returns the current mesh
  20492. */
  20493. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20494. var globalPosition = this.getAbsolutePosition();
  20495. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20496. if (!this._collider) {
  20497. this._collider = new BABYLON.Collider();
  20498. }
  20499. this._collider._radius = this.ellipsoid;
  20500. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20501. return this;
  20502. };
  20503. // Submeshes octree
  20504. /**
  20505. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20506. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20507. * @param maxCapacity defines the maximum size of each block (64 by default)
  20508. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20509. * @returns the new octree
  20510. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20511. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20512. */
  20513. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20514. if (maxCapacity === void 0) { maxCapacity = 64; }
  20515. if (maxDepth === void 0) { maxDepth = 2; }
  20516. if (!this._submeshesOctree) {
  20517. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20518. }
  20519. this.computeWorldMatrix(true);
  20520. var boundingInfo = this.getBoundingInfo();
  20521. // Update octree
  20522. var bbox = boundingInfo.boundingBox;
  20523. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20524. return this._submeshesOctree;
  20525. };
  20526. // Collisions
  20527. /** @hidden */
  20528. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20529. this._generatePointsArray();
  20530. if (!this._positions) {
  20531. return this;
  20532. }
  20533. // Transformation
  20534. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20535. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20536. subMesh._lastColliderWorldVertices = [];
  20537. subMesh._trianglePlanes = [];
  20538. var start = subMesh.verticesStart;
  20539. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20540. for (var i = start; i < end; i++) {
  20541. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20542. }
  20543. }
  20544. // Collide
  20545. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20546. if (collider.collisionFound) {
  20547. collider.collidedMesh = this;
  20548. }
  20549. return this;
  20550. };
  20551. /** @hidden */
  20552. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20553. var subMeshes;
  20554. var len;
  20555. // Octrees
  20556. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20557. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20558. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20559. len = intersections.length;
  20560. subMeshes = intersections.data;
  20561. }
  20562. else {
  20563. subMeshes = this.subMeshes;
  20564. len = subMeshes.length;
  20565. }
  20566. for (var index = 0; index < len; index++) {
  20567. var subMesh = subMeshes[index];
  20568. // Bounding test
  20569. if (len > 1 && !subMesh._checkCollision(collider))
  20570. continue;
  20571. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20572. }
  20573. return this;
  20574. };
  20575. /** @hidden */
  20576. AbstractMesh.prototype._checkCollision = function (collider) {
  20577. // Bounding box test
  20578. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20579. return this;
  20580. // Transformation matrix
  20581. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20582. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20583. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20584. return this;
  20585. };
  20586. // Picking
  20587. /** @hidden */
  20588. AbstractMesh.prototype._generatePointsArray = function () {
  20589. return false;
  20590. };
  20591. /**
  20592. * Checks if the passed Ray intersects with the mesh
  20593. * @param ray defines the ray to use
  20594. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20595. * @returns the picking info
  20596. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20597. */
  20598. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20599. var pickingInfo = new BABYLON.PickingInfo();
  20600. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20601. return pickingInfo;
  20602. }
  20603. if (!this._generatePointsArray()) {
  20604. return pickingInfo;
  20605. }
  20606. var intersectInfo = null;
  20607. // Octrees
  20608. var subMeshes;
  20609. var len;
  20610. if (this._submeshesOctree && this.useOctreeForPicking) {
  20611. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20612. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20613. len = intersections.length;
  20614. subMeshes = intersections.data;
  20615. }
  20616. else {
  20617. subMeshes = this.subMeshes;
  20618. len = subMeshes.length;
  20619. }
  20620. for (var index = 0; index < len; index++) {
  20621. var subMesh = subMeshes[index];
  20622. // Bounding test
  20623. if (len > 1 && !subMesh.canIntersects(ray))
  20624. continue;
  20625. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20626. if (currentIntersectInfo) {
  20627. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20628. intersectInfo = currentIntersectInfo;
  20629. intersectInfo.subMeshId = index;
  20630. if (fastCheck) {
  20631. break;
  20632. }
  20633. }
  20634. }
  20635. }
  20636. if (intersectInfo) {
  20637. // Get picked point
  20638. var world = this.getWorldMatrix();
  20639. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20640. var direction = ray.direction.clone();
  20641. direction = direction.scale(intersectInfo.distance);
  20642. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20643. var pickedPoint = worldOrigin.add(worldDirection);
  20644. // Return result
  20645. pickingInfo.hit = true;
  20646. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20647. pickingInfo.pickedPoint = pickedPoint;
  20648. pickingInfo.pickedMesh = this;
  20649. pickingInfo.bu = intersectInfo.bu || 0;
  20650. pickingInfo.bv = intersectInfo.bv || 0;
  20651. pickingInfo.faceId = intersectInfo.faceId;
  20652. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20653. return pickingInfo;
  20654. }
  20655. return pickingInfo;
  20656. };
  20657. /**
  20658. * Clones the current mesh
  20659. * @param name defines the mesh name
  20660. * @param newParent defines the new mesh parent
  20661. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20662. * @returns the new mesh
  20663. */
  20664. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20665. return null;
  20666. };
  20667. /**
  20668. * Disposes all the submeshes of the current meshnp
  20669. * @returns the current mesh
  20670. */
  20671. AbstractMesh.prototype.releaseSubMeshes = function () {
  20672. if (this.subMeshes) {
  20673. while (this.subMeshes.length) {
  20674. this.subMeshes[0].dispose();
  20675. }
  20676. }
  20677. else {
  20678. this.subMeshes = new Array();
  20679. }
  20680. return this;
  20681. };
  20682. /**
  20683. * Releases resources associated with this abstract mesh.
  20684. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20685. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20686. */
  20687. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20688. var _this = this;
  20689. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20690. var index;
  20691. // Smart Array Retainers.
  20692. this.getScene().freeActiveMeshes();
  20693. this.getScene().freeRenderingGroups();
  20694. // Action manager
  20695. if (this.actionManager !== undefined && this.actionManager !== null) {
  20696. this.actionManager.dispose();
  20697. this.actionManager = null;
  20698. }
  20699. // Skeleton
  20700. this._skeleton = null;
  20701. // Physics
  20702. if (this.physicsImpostor) {
  20703. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20704. }
  20705. // Intersections in progress
  20706. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20707. var other = this._intersectionsInProgress[index];
  20708. var pos = other._intersectionsInProgress.indexOf(this);
  20709. other._intersectionsInProgress.splice(pos, 1);
  20710. }
  20711. this._intersectionsInProgress = [];
  20712. // Lights
  20713. var lights = this.getScene().lights;
  20714. lights.forEach(function (light) {
  20715. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20716. if (meshIndex !== -1) {
  20717. light.includedOnlyMeshes.splice(meshIndex, 1);
  20718. }
  20719. meshIndex = light.excludedMeshes.indexOf(_this);
  20720. if (meshIndex !== -1) {
  20721. light.excludedMeshes.splice(meshIndex, 1);
  20722. }
  20723. // Shadow generators
  20724. var generator = light.getShadowGenerator();
  20725. if (generator) {
  20726. var shadowMap = generator.getShadowMap();
  20727. if (shadowMap && shadowMap.renderList) {
  20728. meshIndex = shadowMap.renderList.indexOf(_this);
  20729. if (meshIndex !== -1) {
  20730. shadowMap.renderList.splice(meshIndex, 1);
  20731. }
  20732. }
  20733. }
  20734. });
  20735. // Edges
  20736. if (this._edgesRenderer) {
  20737. this._edgesRenderer.dispose();
  20738. this._edgesRenderer = null;
  20739. }
  20740. // SubMeshes
  20741. if (this.getClassName() !== "InstancedMesh") {
  20742. this.releaseSubMeshes();
  20743. }
  20744. // Octree
  20745. var sceneOctree = this.getScene().selectionOctree;
  20746. if (sceneOctree !== undefined && sceneOctree !== null) {
  20747. var index = sceneOctree.dynamicContent.indexOf(this);
  20748. if (index !== -1) {
  20749. sceneOctree.dynamicContent.splice(index, 1);
  20750. }
  20751. }
  20752. // Query
  20753. var engine = this.getScene().getEngine();
  20754. if (this._occlusionQuery) {
  20755. this._isOcclusionQueryInProgress = false;
  20756. engine.deleteQuery(this._occlusionQuery);
  20757. this._occlusionQuery = null;
  20758. }
  20759. // Engine
  20760. engine.wipeCaches();
  20761. // Remove from scene
  20762. this.getScene().removeMesh(this);
  20763. if (disposeMaterialAndTextures) {
  20764. if (this.material) {
  20765. this.material.dispose(false, true);
  20766. }
  20767. }
  20768. if (!doNotRecurse) {
  20769. // Particles
  20770. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20771. if (this.getScene().particleSystems[index].emitter === this) {
  20772. this.getScene().particleSystems[index].dispose();
  20773. index--;
  20774. }
  20775. }
  20776. }
  20777. // facet data
  20778. if (this._facetDataEnabled) {
  20779. this.disableFacetData();
  20780. }
  20781. this.onAfterWorldMatrixUpdateObservable.clear();
  20782. this.onCollideObservable.clear();
  20783. this.onCollisionPositionChangeObservable.clear();
  20784. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20785. };
  20786. /**
  20787. * Adds the passed mesh as a child to the current mesh
  20788. * @param mesh defines the child mesh
  20789. * @returns the current mesh
  20790. */
  20791. AbstractMesh.prototype.addChild = function (mesh) {
  20792. mesh.setParent(this);
  20793. return this;
  20794. };
  20795. /**
  20796. * Removes the passed mesh from the current mesh children list
  20797. * @param mesh defines the child mesh
  20798. * @returns the current mesh
  20799. */
  20800. AbstractMesh.prototype.removeChild = function (mesh) {
  20801. mesh.setParent(null);
  20802. return this;
  20803. };
  20804. // Facet data
  20805. /** @hidden */
  20806. AbstractMesh.prototype._initFacetData = function () {
  20807. if (!this._facetNormals) {
  20808. this._facetNormals = new Array();
  20809. }
  20810. if (!this._facetPositions) {
  20811. this._facetPositions = new Array();
  20812. }
  20813. if (!this._facetPartitioning) {
  20814. this._facetPartitioning = new Array();
  20815. }
  20816. this._facetNb = (this.getIndices().length / 3) | 0;
  20817. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20818. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20819. for (var f = 0; f < this._facetNb; f++) {
  20820. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20821. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20822. }
  20823. this._facetDataEnabled = true;
  20824. return this;
  20825. };
  20826. /**
  20827. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20828. * This method can be called within the render loop.
  20829. * 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
  20830. * @returns the current mesh
  20831. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20832. */
  20833. AbstractMesh.prototype.updateFacetData = function () {
  20834. if (!this._facetDataEnabled) {
  20835. this._initFacetData();
  20836. }
  20837. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20838. var indices = this.getIndices();
  20839. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20840. var bInfo = this.getBoundingInfo();
  20841. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20842. // init arrays, matrix and sort function on first call
  20843. this._facetDepthSortEnabled = true;
  20844. if (indices instanceof Uint16Array) {
  20845. this._depthSortedIndices = new Uint16Array(indices);
  20846. }
  20847. else if (indices instanceof Uint32Array) {
  20848. this._depthSortedIndices = new Uint32Array(indices);
  20849. }
  20850. else {
  20851. var needs32bits = false;
  20852. for (var i = 0; i < indices.length; i++) {
  20853. if (indices[i] > 65535) {
  20854. needs32bits = true;
  20855. break;
  20856. }
  20857. }
  20858. if (needs32bits) {
  20859. this._depthSortedIndices = new Uint32Array(indices);
  20860. }
  20861. else {
  20862. this._depthSortedIndices = new Uint16Array(indices);
  20863. }
  20864. }
  20865. this._facetDepthSortFunction = function (f1, f2) {
  20866. return (f2.sqDistance - f1.sqDistance);
  20867. };
  20868. if (!this._facetDepthSortFrom) {
  20869. var camera = this.getScene().activeCamera;
  20870. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20871. }
  20872. this._depthSortedFacets = [];
  20873. for (var f = 0; f < this._facetNb; f++) {
  20874. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20875. this._depthSortedFacets.push(depthSortedFacet);
  20876. }
  20877. this._invertedMatrix = BABYLON.Matrix.Identity();
  20878. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20879. }
  20880. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20881. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20882. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20883. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20884. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20885. this._subDiv.max = this._partitioningSubdivisions;
  20886. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20887. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20888. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20889. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20890. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20891. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20892. // set the parameters for ComputeNormals()
  20893. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20894. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20895. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20896. this._facetParameters.bInfo = bInfo;
  20897. this._facetParameters.bbSize = this._bbSize;
  20898. this._facetParameters.subDiv = this._subDiv;
  20899. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20900. this._facetParameters.depthSort = this._facetDepthSort;
  20901. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20902. this.computeWorldMatrix(true);
  20903. this._worldMatrix.invertToRef(this._invertedMatrix);
  20904. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20905. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20906. }
  20907. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20908. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20909. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20910. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20911. var l = (this._depthSortedIndices.length / 3) | 0;
  20912. for (var f = 0; f < l; f++) {
  20913. var sind = this._depthSortedFacets[f].ind;
  20914. this._depthSortedIndices[f * 3] = indices[sind];
  20915. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20916. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20917. }
  20918. this.updateIndices(this._depthSortedIndices);
  20919. }
  20920. return this;
  20921. };
  20922. /**
  20923. * Returns the facetLocalNormals array.
  20924. * The normals are expressed in the mesh local spac
  20925. * @returns an array of Vector3
  20926. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20927. */
  20928. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20929. if (!this._facetNormals) {
  20930. this.updateFacetData();
  20931. }
  20932. return this._facetNormals;
  20933. };
  20934. /**
  20935. * Returns the facetLocalPositions array.
  20936. * The facet positions are expressed in the mesh local space
  20937. * @returns an array of Vector3
  20938. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20939. */
  20940. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20941. if (!this._facetPositions) {
  20942. this.updateFacetData();
  20943. }
  20944. return this._facetPositions;
  20945. };
  20946. /**
  20947. * Returns the facetLocalPartioning array
  20948. * @returns an array of array of numbers
  20949. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20950. */
  20951. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20952. if (!this._facetPartitioning) {
  20953. this.updateFacetData();
  20954. }
  20955. return this._facetPartitioning;
  20956. };
  20957. /**
  20958. * Returns the i-th facet position in the world system.
  20959. * This method allocates a new Vector3 per call
  20960. * @param i defines the facet index
  20961. * @returns a new Vector3
  20962. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20963. */
  20964. AbstractMesh.prototype.getFacetPosition = function (i) {
  20965. var pos = BABYLON.Vector3.Zero();
  20966. this.getFacetPositionToRef(i, pos);
  20967. return pos;
  20968. };
  20969. /**
  20970. * Sets the reference Vector3 with the i-th facet position in the world system
  20971. * @param i defines the facet index
  20972. * @param ref defines the target vector
  20973. * @returns the current mesh
  20974. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20975. */
  20976. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20977. var localPos = (this.getFacetLocalPositions())[i];
  20978. var world = this.getWorldMatrix();
  20979. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20980. return this;
  20981. };
  20982. /**
  20983. * Returns the i-th facet normal in the world system.
  20984. * This method allocates a new Vector3 per call
  20985. * @param i defines the facet index
  20986. * @returns a new Vector3
  20987. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20988. */
  20989. AbstractMesh.prototype.getFacetNormal = function (i) {
  20990. var norm = BABYLON.Vector3.Zero();
  20991. this.getFacetNormalToRef(i, norm);
  20992. return norm;
  20993. };
  20994. /**
  20995. * Sets the reference Vector3 with the i-th facet normal in the world system
  20996. * @param i defines the facet index
  20997. * @param ref defines the target vector
  20998. * @returns the current mesh
  20999. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21000. */
  21001. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21002. var localNorm = (this.getFacetLocalNormals())[i];
  21003. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21004. return this;
  21005. };
  21006. /**
  21007. * 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)
  21008. * @param x defines x coordinate
  21009. * @param y defines y coordinate
  21010. * @param z defines z coordinate
  21011. * @returns the array of facet indexes
  21012. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21013. */
  21014. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21015. var bInfo = this.getBoundingInfo();
  21016. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21017. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21018. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21019. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21020. return null;
  21021. }
  21022. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21023. };
  21024. /**
  21025. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21026. * @param projected sets as the (x,y,z) world projection on the facet
  21027. * @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
  21028. * @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
  21029. * @param x defines x coordinate
  21030. * @param y defines y coordinate
  21031. * @param z defines z coordinate
  21032. * @returns the face index if found (or null instead)
  21033. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21034. */
  21035. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21036. if (checkFace === void 0) { checkFace = false; }
  21037. if (facing === void 0) { facing = true; }
  21038. var world = this.getWorldMatrix();
  21039. var invMat = BABYLON.Tmp.Matrix[5];
  21040. world.invertToRef(invMat);
  21041. var invVect = BABYLON.Tmp.Vector3[8];
  21042. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21043. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21044. if (projected) {
  21045. // tranform the local computed projected vector to world coordinates
  21046. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21047. }
  21048. return closest;
  21049. };
  21050. /**
  21051. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21052. * @param projected sets as the (x,y,z) local projection on the facet
  21053. * @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
  21054. * @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
  21055. * @param x defines x coordinate
  21056. * @param y defines y coordinate
  21057. * @param z defines z coordinate
  21058. * @returns the face index if found (or null instead)
  21059. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21060. */
  21061. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21062. if (checkFace === void 0) { checkFace = false; }
  21063. if (facing === void 0) { facing = true; }
  21064. var closest = null;
  21065. var tmpx = 0.0;
  21066. var tmpy = 0.0;
  21067. var tmpz = 0.0;
  21068. var d = 0.0; // tmp dot facet normal * facet position
  21069. var t0 = 0.0;
  21070. var projx = 0.0;
  21071. var projy = 0.0;
  21072. var projz = 0.0;
  21073. // Get all the facets in the same partitioning block than (x, y, z)
  21074. var facetPositions = this.getFacetLocalPositions();
  21075. var facetNormals = this.getFacetLocalNormals();
  21076. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21077. if (!facetsInBlock) {
  21078. return null;
  21079. }
  21080. // Get the closest facet to (x, y, z)
  21081. var shortest = Number.MAX_VALUE; // init distance vars
  21082. var tmpDistance = shortest;
  21083. var fib; // current facet in the block
  21084. var norm; // current facet normal
  21085. var p0; // current facet barycenter position
  21086. // loop on all the facets in the current partitioning block
  21087. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21088. fib = facetsInBlock[idx];
  21089. norm = facetNormals[fib];
  21090. p0 = facetPositions[fib];
  21091. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21092. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21093. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21094. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21095. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21096. projx = x + norm.x * t0;
  21097. projy = y + norm.y * t0;
  21098. projz = z + norm.z * t0;
  21099. tmpx = projx - x;
  21100. tmpy = projy - y;
  21101. tmpz = projz - z;
  21102. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21103. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21104. shortest = tmpDistance;
  21105. closest = fib;
  21106. if (projected) {
  21107. projected.x = projx;
  21108. projected.y = projy;
  21109. projected.z = projz;
  21110. }
  21111. }
  21112. }
  21113. }
  21114. return closest;
  21115. };
  21116. /**
  21117. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21118. * @returns the parameters
  21119. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21120. */
  21121. AbstractMesh.prototype.getFacetDataParameters = function () {
  21122. return this._facetParameters;
  21123. };
  21124. /**
  21125. * Disables the feature FacetData and frees the related memory
  21126. * @returns the current mesh
  21127. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21128. */
  21129. AbstractMesh.prototype.disableFacetData = function () {
  21130. if (this._facetDataEnabled) {
  21131. this._facetDataEnabled = false;
  21132. this._facetPositions = new Array();
  21133. this._facetNormals = new Array();
  21134. this._facetPartitioning = new Array();
  21135. this._facetParameters = null;
  21136. this._depthSortedIndices = new Uint32Array(0);
  21137. }
  21138. return this;
  21139. };
  21140. /**
  21141. * Updates the AbstractMesh indices array
  21142. * @param indices defines the data source
  21143. * @returns the current mesh
  21144. */
  21145. AbstractMesh.prototype.updateIndices = function (indices) {
  21146. return this;
  21147. };
  21148. /**
  21149. * Creates new normals data for the mesh
  21150. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21151. * @returns the current mesh
  21152. */
  21153. AbstractMesh.prototype.createNormals = function (updatable) {
  21154. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21155. var indices = this.getIndices();
  21156. var normals;
  21157. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21158. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21159. }
  21160. else {
  21161. normals = [];
  21162. }
  21163. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21164. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21165. return this;
  21166. };
  21167. /**
  21168. * Align the mesh with a normal
  21169. * @param normal defines the normal to use
  21170. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21171. * @returns the current mesh
  21172. */
  21173. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21174. if (!upDirection) {
  21175. upDirection = BABYLON.Axis.Y;
  21176. }
  21177. var axisX = BABYLON.Tmp.Vector3[0];
  21178. var axisZ = BABYLON.Tmp.Vector3[1];
  21179. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21180. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21181. if (this.rotationQuaternion) {
  21182. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21183. }
  21184. else {
  21185. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21186. }
  21187. return this;
  21188. };
  21189. /** @hidden */
  21190. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21191. this._isOccluded = false;
  21192. };
  21193. /** No occlusion */
  21194. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21195. /** Occlusion set to optimisitic */
  21196. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21197. /** Occlusion set to strict */
  21198. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21199. /** Use an accurante occlusion algorithm */
  21200. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21201. /** Use a conservative occlusion algorithm */
  21202. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21203. return AbstractMesh;
  21204. }(BABYLON.TransformNode));
  21205. BABYLON.AbstractMesh = AbstractMesh;
  21206. })(BABYLON || (BABYLON = {}));
  21207. //# sourceMappingURL=babylon.abstractMesh.js.map
  21208. var BABYLON;
  21209. (function (BABYLON) {
  21210. /**
  21211. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21212. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21213. * 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.
  21214. */
  21215. var Light = /** @class */ (function (_super) {
  21216. __extends(Light, _super);
  21217. /**
  21218. * Creates a Light object in the scene.
  21219. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21220. * @param name The firendly name of the light
  21221. * @param scene The scene the light belongs too
  21222. */
  21223. function Light(name, scene) {
  21224. var _this = _super.call(this, name, scene) || this;
  21225. /**
  21226. * Diffuse gives the basic color to an object.
  21227. */
  21228. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21229. /**
  21230. * Specular produces a highlight color on an object.
  21231. * Note: This is note affecting PBR materials.
  21232. */
  21233. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21234. /**
  21235. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21236. * falling off base on range or angle.
  21237. * This can be set to any values in Light.FALLOFF_x.
  21238. *
  21239. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21240. * other types of materials.
  21241. */
  21242. _this.falloffType = Light.FALLOFF_DEFAULT;
  21243. /**
  21244. * Strength of the light.
  21245. * Note: By default it is define in the framework own unit.
  21246. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21247. */
  21248. _this.intensity = 1.0;
  21249. _this._range = Number.MAX_VALUE;
  21250. _this._inverseSquaredRange = 0;
  21251. /**
  21252. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21253. * of light.
  21254. */
  21255. _this._photometricScale = 1.0;
  21256. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21257. _this._radius = 0.00001;
  21258. /**
  21259. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21260. * exceeding the number allowed of the materials.
  21261. */
  21262. _this.renderPriority = 0;
  21263. _this._shadowEnabled = true;
  21264. _this._excludeWithLayerMask = 0;
  21265. _this._includeOnlyWithLayerMask = 0;
  21266. _this._lightmapMode = 0;
  21267. /**
  21268. * @hidden Internal use only.
  21269. */
  21270. _this._excludedMeshesIds = new Array();
  21271. /**
  21272. * @hidden Internal use only.
  21273. */
  21274. _this._includedOnlyMeshesIds = new Array();
  21275. _this.getScene().addLight(_this);
  21276. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21277. _this._buildUniformLayout();
  21278. _this.includedOnlyMeshes = new Array();
  21279. _this.excludedMeshes = new Array();
  21280. _this._resyncMeshes();
  21281. return _this;
  21282. }
  21283. Object.defineProperty(Light.prototype, "range", {
  21284. /**
  21285. * Defines how far from the source the light is impacting in scene units.
  21286. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21287. */
  21288. get: function () {
  21289. return this._range;
  21290. },
  21291. /**
  21292. * Defines how far from the source the light is impacting in scene units.
  21293. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21294. */
  21295. set: function (value) {
  21296. this._range = value;
  21297. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21298. },
  21299. enumerable: true,
  21300. configurable: true
  21301. });
  21302. Object.defineProperty(Light.prototype, "intensityMode", {
  21303. /**
  21304. * Gets the photometric scale used to interpret the intensity.
  21305. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21306. */
  21307. get: function () {
  21308. return this._intensityMode;
  21309. },
  21310. /**
  21311. * Sets the photometric scale used to interpret the intensity.
  21312. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21313. */
  21314. set: function (value) {
  21315. this._intensityMode = value;
  21316. this._computePhotometricScale();
  21317. },
  21318. enumerable: true,
  21319. configurable: true
  21320. });
  21321. ;
  21322. ;
  21323. Object.defineProperty(Light.prototype, "radius", {
  21324. /**
  21325. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21326. */
  21327. get: function () {
  21328. return this._radius;
  21329. },
  21330. /**
  21331. * sets the light radius used by PBR Materials to simulate soft area lights.
  21332. */
  21333. set: function (value) {
  21334. this._radius = value;
  21335. this._computePhotometricScale();
  21336. },
  21337. enumerable: true,
  21338. configurable: true
  21339. });
  21340. ;
  21341. ;
  21342. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21343. /**
  21344. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21345. * the current shadow generator.
  21346. */
  21347. get: function () {
  21348. return this._shadowEnabled;
  21349. },
  21350. /**
  21351. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21352. * the current shadow generator.
  21353. */
  21354. set: function (value) {
  21355. if (this._shadowEnabled === value) {
  21356. return;
  21357. }
  21358. this._shadowEnabled = value;
  21359. this._markMeshesAsLightDirty();
  21360. },
  21361. enumerable: true,
  21362. configurable: true
  21363. });
  21364. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21365. /**
  21366. * Gets the only meshes impacted by this light.
  21367. */
  21368. get: function () {
  21369. return this._includedOnlyMeshes;
  21370. },
  21371. /**
  21372. * Sets the only meshes impacted by this light.
  21373. */
  21374. set: function (value) {
  21375. this._includedOnlyMeshes = value;
  21376. this._hookArrayForIncludedOnly(value);
  21377. },
  21378. enumerable: true,
  21379. configurable: true
  21380. });
  21381. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21382. /**
  21383. * Gets the meshes not impacted by this light.
  21384. */
  21385. get: function () {
  21386. return this._excludedMeshes;
  21387. },
  21388. /**
  21389. * Sets the meshes not impacted by this light.
  21390. */
  21391. set: function (value) {
  21392. this._excludedMeshes = value;
  21393. this._hookArrayForExcluded(value);
  21394. },
  21395. enumerable: true,
  21396. configurable: true
  21397. });
  21398. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21399. /**
  21400. * Gets the layer id use to find what meshes are not impacted by the light.
  21401. * Inactive if 0
  21402. */
  21403. get: function () {
  21404. return this._excludeWithLayerMask;
  21405. },
  21406. /**
  21407. * Sets the layer id use to find what meshes are not impacted by the light.
  21408. * Inactive if 0
  21409. */
  21410. set: function (value) {
  21411. this._excludeWithLayerMask = value;
  21412. this._resyncMeshes();
  21413. },
  21414. enumerable: true,
  21415. configurable: true
  21416. });
  21417. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21418. /**
  21419. * Gets the layer id use to find what meshes are impacted by the light.
  21420. * Inactive if 0
  21421. */
  21422. get: function () {
  21423. return this._includeOnlyWithLayerMask;
  21424. },
  21425. /**
  21426. * Sets the layer id use to find what meshes are impacted by the light.
  21427. * Inactive if 0
  21428. */
  21429. set: function (value) {
  21430. this._includeOnlyWithLayerMask = value;
  21431. this._resyncMeshes();
  21432. },
  21433. enumerable: true,
  21434. configurable: true
  21435. });
  21436. Object.defineProperty(Light.prototype, "lightmapMode", {
  21437. /**
  21438. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21439. */
  21440. get: function () {
  21441. return this._lightmapMode;
  21442. },
  21443. /**
  21444. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21445. */
  21446. set: function (value) {
  21447. if (this._lightmapMode === value) {
  21448. return;
  21449. }
  21450. this._lightmapMode = value;
  21451. this._markMeshesAsLightDirty();
  21452. },
  21453. enumerable: true,
  21454. configurable: true
  21455. });
  21456. /**
  21457. * Returns the string "Light".
  21458. * @returns the class name
  21459. */
  21460. Light.prototype.getClassName = function () {
  21461. return "Light";
  21462. };
  21463. /**
  21464. * Converts the light information to a readable string for debug purpose.
  21465. * @param fullDetails Supports for multiple levels of logging within scene loading
  21466. * @returns the human readable light info
  21467. */
  21468. Light.prototype.toString = function (fullDetails) {
  21469. var ret = "Name: " + this.name;
  21470. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21471. if (this.animations) {
  21472. for (var i = 0; i < this.animations.length; i++) {
  21473. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21474. }
  21475. }
  21476. if (fullDetails) {
  21477. }
  21478. return ret;
  21479. };
  21480. /**
  21481. * Set the enabled state of this node.
  21482. * @param value - the new enabled state
  21483. */
  21484. Light.prototype.setEnabled = function (value) {
  21485. _super.prototype.setEnabled.call(this, value);
  21486. this._resyncMeshes();
  21487. };
  21488. /**
  21489. * Returns the Light associated shadow generator if any.
  21490. * @return the associated shadow generator.
  21491. */
  21492. Light.prototype.getShadowGenerator = function () {
  21493. return this._shadowGenerator;
  21494. };
  21495. /**
  21496. * Returns a Vector3, the absolute light position in the World.
  21497. * @returns the world space position of the light
  21498. */
  21499. Light.prototype.getAbsolutePosition = function () {
  21500. return BABYLON.Vector3.Zero();
  21501. };
  21502. /**
  21503. * Specifies if the light will affect the passed mesh.
  21504. * @param mesh The mesh to test against the light
  21505. * @return true the mesh is affected otherwise, false.
  21506. */
  21507. Light.prototype.canAffectMesh = function (mesh) {
  21508. if (!mesh) {
  21509. return true;
  21510. }
  21511. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21512. return false;
  21513. }
  21514. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21515. return false;
  21516. }
  21517. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21518. return false;
  21519. }
  21520. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21521. return false;
  21522. }
  21523. return true;
  21524. };
  21525. /**
  21526. * Computes and Returns the light World matrix.
  21527. * @returns the world matrix
  21528. */
  21529. Light.prototype.getWorldMatrix = function () {
  21530. this._currentRenderId = this.getScene().getRenderId();
  21531. this._childRenderId = this._currentRenderId;
  21532. var worldMatrix = this._getWorldMatrix();
  21533. if (this.parent && this.parent.getWorldMatrix) {
  21534. if (!this._parentedWorldMatrix) {
  21535. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21536. }
  21537. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21538. this._markSyncedWithParent();
  21539. return this._parentedWorldMatrix;
  21540. }
  21541. return worldMatrix;
  21542. };
  21543. /**
  21544. * Sort function to order lights for rendering.
  21545. * @param a First Light object to compare to second.
  21546. * @param b Second Light object to compare first.
  21547. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21548. */
  21549. Light.CompareLightsPriority = function (a, b) {
  21550. //shadow-casting lights have priority over non-shadow-casting lights
  21551. //the renderPrioirty is a secondary sort criterion
  21552. if (a.shadowEnabled !== b.shadowEnabled) {
  21553. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21554. }
  21555. return b.renderPriority - a.renderPriority;
  21556. };
  21557. /**
  21558. * Releases resources associated with this node.
  21559. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21560. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21561. */
  21562. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21563. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21564. if (this._shadowGenerator) {
  21565. this._shadowGenerator.dispose();
  21566. this._shadowGenerator = null;
  21567. }
  21568. // Animations
  21569. this.getScene().stopAnimation(this);
  21570. // Remove from meshes
  21571. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21572. var mesh = _a[_i];
  21573. mesh._removeLightSource(this);
  21574. }
  21575. this._uniformBuffer.dispose();
  21576. // Remove from scene
  21577. this.getScene().removeLight(this);
  21578. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21579. };
  21580. /**
  21581. * Returns the light type ID (integer).
  21582. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21583. */
  21584. Light.prototype.getTypeID = function () {
  21585. return 0;
  21586. };
  21587. /**
  21588. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21589. * @returns the scaled intensity in intensity mode unit
  21590. */
  21591. Light.prototype.getScaledIntensity = function () {
  21592. return this._photometricScale * this.intensity;
  21593. };
  21594. /**
  21595. * Returns a new Light object, named "name", from the current one.
  21596. * @param name The name of the cloned light
  21597. * @returns the new created light
  21598. */
  21599. Light.prototype.clone = function (name) {
  21600. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21601. if (!constructor) {
  21602. return null;
  21603. }
  21604. return BABYLON.SerializationHelper.Clone(constructor, this);
  21605. };
  21606. /**
  21607. * Serializes the current light into a Serialization object.
  21608. * @returns the serialized object.
  21609. */
  21610. Light.prototype.serialize = function () {
  21611. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21612. // Type
  21613. serializationObject.type = this.getTypeID();
  21614. // Parent
  21615. if (this.parent) {
  21616. serializationObject.parentId = this.parent.id;
  21617. }
  21618. // Inclusion / exclusions
  21619. if (this.excludedMeshes.length > 0) {
  21620. serializationObject.excludedMeshesIds = [];
  21621. this.excludedMeshes.forEach(function (mesh) {
  21622. serializationObject.excludedMeshesIds.push(mesh.id);
  21623. });
  21624. }
  21625. if (this.includedOnlyMeshes.length > 0) {
  21626. serializationObject.includedOnlyMeshesIds = [];
  21627. this.includedOnlyMeshes.forEach(function (mesh) {
  21628. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21629. });
  21630. }
  21631. // Animations
  21632. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21633. serializationObject.ranges = this.serializeAnimationRanges();
  21634. return serializationObject;
  21635. };
  21636. /**
  21637. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21638. * This new light is named "name" and added to the passed scene.
  21639. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21640. * @param name The friendly name of the light
  21641. * @param scene The scene the new light will belong to
  21642. * @returns the constructor function
  21643. */
  21644. Light.GetConstructorFromName = function (type, name, scene) {
  21645. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21646. if (constructorFunc) {
  21647. return constructorFunc;
  21648. }
  21649. // Default to no light for none present once.
  21650. return null;
  21651. };
  21652. /**
  21653. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21654. * @param parsedLight The JSON representation of the light
  21655. * @param scene The scene to create the parsed light in
  21656. * @returns the created light after parsing
  21657. */
  21658. Light.Parse = function (parsedLight, scene) {
  21659. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21660. if (!constructor) {
  21661. return null;
  21662. }
  21663. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21664. // Inclusion / exclusions
  21665. if (parsedLight.excludedMeshesIds) {
  21666. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21667. }
  21668. if (parsedLight.includedOnlyMeshesIds) {
  21669. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21670. }
  21671. // Parent
  21672. if (parsedLight.parentId) {
  21673. light._waitingParentId = parsedLight.parentId;
  21674. }
  21675. // Animations
  21676. if (parsedLight.animations) {
  21677. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21678. var parsedAnimation = parsedLight.animations[animationIndex];
  21679. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21680. }
  21681. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21682. }
  21683. if (parsedLight.autoAnimate) {
  21684. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21685. }
  21686. return light;
  21687. };
  21688. Light.prototype._hookArrayForExcluded = function (array) {
  21689. var _this = this;
  21690. var oldPush = array.push;
  21691. array.push = function () {
  21692. var items = [];
  21693. for (var _i = 0; _i < arguments.length; _i++) {
  21694. items[_i] = arguments[_i];
  21695. }
  21696. var result = oldPush.apply(array, items);
  21697. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21698. var item = items_1[_a];
  21699. item._resyncLighSource(_this);
  21700. }
  21701. return result;
  21702. };
  21703. var oldSplice = array.splice;
  21704. array.splice = function (index, deleteCount) {
  21705. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21706. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21707. var item = deleted_1[_i];
  21708. item._resyncLighSource(_this);
  21709. }
  21710. return deleted;
  21711. };
  21712. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21713. var item = array_1[_i];
  21714. item._resyncLighSource(this);
  21715. }
  21716. };
  21717. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21718. var _this = this;
  21719. var oldPush = array.push;
  21720. array.push = function () {
  21721. var items = [];
  21722. for (var _i = 0; _i < arguments.length; _i++) {
  21723. items[_i] = arguments[_i];
  21724. }
  21725. var result = oldPush.apply(array, items);
  21726. _this._resyncMeshes();
  21727. return result;
  21728. };
  21729. var oldSplice = array.splice;
  21730. array.splice = function (index, deleteCount) {
  21731. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21732. _this._resyncMeshes();
  21733. return deleted;
  21734. };
  21735. this._resyncMeshes();
  21736. };
  21737. Light.prototype._resyncMeshes = function () {
  21738. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21739. var mesh = _a[_i];
  21740. mesh._resyncLighSource(this);
  21741. }
  21742. };
  21743. /**
  21744. * Forces the meshes to update their light related information in their rendering used effects
  21745. * @hidden Internal Use Only
  21746. */
  21747. Light.prototype._markMeshesAsLightDirty = function () {
  21748. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21749. var mesh = _a[_i];
  21750. if (mesh._lightSources.indexOf(this) !== -1) {
  21751. mesh._markSubMeshesAsLightDirty();
  21752. }
  21753. }
  21754. };
  21755. /**
  21756. * Recomputes the cached photometric scale if needed.
  21757. */
  21758. Light.prototype._computePhotometricScale = function () {
  21759. this._photometricScale = this._getPhotometricScale();
  21760. this.getScene().resetCachedMaterial();
  21761. };
  21762. /**
  21763. * Returns the Photometric Scale according to the light type and intensity mode.
  21764. */
  21765. Light.prototype._getPhotometricScale = function () {
  21766. var photometricScale = 0.0;
  21767. var lightTypeID = this.getTypeID();
  21768. //get photometric mode
  21769. var photometricMode = this.intensityMode;
  21770. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21771. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21772. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21773. }
  21774. else {
  21775. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21776. }
  21777. }
  21778. //compute photometric scale
  21779. switch (lightTypeID) {
  21780. case Light.LIGHTTYPEID_POINTLIGHT:
  21781. case Light.LIGHTTYPEID_SPOTLIGHT:
  21782. switch (photometricMode) {
  21783. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21784. photometricScale = 1.0 / (4.0 * Math.PI);
  21785. break;
  21786. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21787. photometricScale = 1.0;
  21788. break;
  21789. case Light.INTENSITYMODE_LUMINANCE:
  21790. photometricScale = this.radius * this.radius;
  21791. break;
  21792. }
  21793. break;
  21794. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21795. switch (photometricMode) {
  21796. case Light.INTENSITYMODE_ILLUMINANCE:
  21797. photometricScale = 1.0;
  21798. break;
  21799. case Light.INTENSITYMODE_LUMINANCE:
  21800. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21801. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21802. var apexAngleRadians = this.radius;
  21803. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21804. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21805. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21806. photometricScale = solidAngle;
  21807. break;
  21808. }
  21809. break;
  21810. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21811. // No fall off in hemisperic light.
  21812. photometricScale = 1.0;
  21813. break;
  21814. }
  21815. return photometricScale;
  21816. };
  21817. /**
  21818. * Reorder the light in the scene according to their defined priority.
  21819. * @hidden Internal Use Only
  21820. */
  21821. Light.prototype._reorderLightsInScene = function () {
  21822. var scene = this.getScene();
  21823. if (this._renderPriority != 0) {
  21824. scene.requireLightSorting = true;
  21825. }
  21826. this.getScene().sortLightsByPriority();
  21827. };
  21828. /**
  21829. * Falloff Default: light is falling off following the material specification:
  21830. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  21831. */
  21832. Light.FALLOFF_DEFAULT = 0;
  21833. /**
  21834. * Falloff Physical: light is falling off following the inverse squared distance law.
  21835. */
  21836. Light.FALLOFF_PHYSICAL = 1;
  21837. /**
  21838. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  21839. * to enhance interoperability with other engines.
  21840. */
  21841. Light.FALLOFF_GLTF = 2;
  21842. /**
  21843. * Falloff Standard: light is falling off like in the standard material
  21844. * to enhance interoperability with other materials.
  21845. */
  21846. Light.FALLOFF_STANDARD = 3;
  21847. //lightmapMode Consts
  21848. /**
  21849. * If every light affecting the material is in this lightmapMode,
  21850. * material.lightmapTexture adds or multiplies
  21851. * (depends on material.useLightmapAsShadowmap)
  21852. * after every other light calculations.
  21853. */
  21854. Light.LIGHTMAP_DEFAULT = 0;
  21855. /**
  21856. * material.lightmapTexture as only diffuse lighting from this light
  21857. * adds only specular lighting from this light
  21858. * adds dynamic shadows
  21859. */
  21860. Light.LIGHTMAP_SPECULAR = 1;
  21861. /**
  21862. * material.lightmapTexture as only lighting
  21863. * no light calculation from this light
  21864. * only adds dynamic shadows from this light
  21865. */
  21866. Light.LIGHTMAP_SHADOWSONLY = 2;
  21867. // Intensity Mode Consts
  21868. /**
  21869. * Each light type uses the default quantity according to its type:
  21870. * point/spot lights use luminous intensity
  21871. * directional lights use illuminance
  21872. */
  21873. Light.INTENSITYMODE_AUTOMATIC = 0;
  21874. /**
  21875. * lumen (lm)
  21876. */
  21877. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21878. /**
  21879. * candela (lm/sr)
  21880. */
  21881. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21882. /**
  21883. * lux (lm/m^2)
  21884. */
  21885. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21886. /**
  21887. * nit (cd/m^2)
  21888. */
  21889. Light.INTENSITYMODE_LUMINANCE = 4;
  21890. // Light types ids const.
  21891. /**
  21892. * Light type const id of the point light.
  21893. */
  21894. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21895. /**
  21896. * Light type const id of the directional light.
  21897. */
  21898. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21899. /**
  21900. * Light type const id of the spot light.
  21901. */
  21902. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21903. /**
  21904. * Light type const id of the hemispheric light.
  21905. */
  21906. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21907. __decorate([
  21908. BABYLON.serializeAsColor3()
  21909. ], Light.prototype, "diffuse", void 0);
  21910. __decorate([
  21911. BABYLON.serializeAsColor3()
  21912. ], Light.prototype, "specular", void 0);
  21913. __decorate([
  21914. BABYLON.serialize()
  21915. ], Light.prototype, "falloffType", void 0);
  21916. __decorate([
  21917. BABYLON.serialize()
  21918. ], Light.prototype, "intensity", void 0);
  21919. __decorate([
  21920. BABYLON.serialize()
  21921. ], Light.prototype, "range", null);
  21922. __decorate([
  21923. BABYLON.serialize()
  21924. ], Light.prototype, "intensityMode", null);
  21925. __decorate([
  21926. BABYLON.serialize()
  21927. ], Light.prototype, "radius", null);
  21928. __decorate([
  21929. BABYLON.serialize()
  21930. ], Light.prototype, "_renderPriority", void 0);
  21931. __decorate([
  21932. BABYLON.expandToProperty("_reorderLightsInScene")
  21933. ], Light.prototype, "renderPriority", void 0);
  21934. __decorate([
  21935. BABYLON.serialize("shadowEnabled")
  21936. ], Light.prototype, "_shadowEnabled", void 0);
  21937. __decorate([
  21938. BABYLON.serialize("excludeWithLayerMask")
  21939. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21940. __decorate([
  21941. BABYLON.serialize("includeOnlyWithLayerMask")
  21942. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21943. __decorate([
  21944. BABYLON.serialize("lightmapMode")
  21945. ], Light.prototype, "_lightmapMode", void 0);
  21946. return Light;
  21947. }(BABYLON.Node));
  21948. BABYLON.Light = Light;
  21949. })(BABYLON || (BABYLON = {}));
  21950. //# sourceMappingURL=babylon.light.js.map
  21951. var BABYLON;
  21952. (function (BABYLON) {
  21953. var Camera = /** @class */ (function (_super) {
  21954. __extends(Camera, _super);
  21955. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21956. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21957. var _this = _super.call(this, name, scene) || this;
  21958. /**
  21959. * The vector the camera should consider as up.
  21960. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21961. */
  21962. _this.upVector = BABYLON.Vector3.Up();
  21963. _this.orthoLeft = null;
  21964. _this.orthoRight = null;
  21965. _this.orthoBottom = null;
  21966. _this.orthoTop = null;
  21967. /**
  21968. * FOV is set in Radians. (default is 0.8)
  21969. */
  21970. _this.fov = 0.8;
  21971. _this.minZ = 1;
  21972. _this.maxZ = 10000.0;
  21973. _this.inertia = 0.9;
  21974. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21975. _this.isIntermediate = false;
  21976. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21977. /**
  21978. * Restricts the camera to viewing objects with the same layerMask.
  21979. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21980. */
  21981. _this.layerMask = 0x0FFFFFFF;
  21982. /**
  21983. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21984. */
  21985. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21986. // Camera rig members
  21987. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21988. /** @hidden */
  21989. _this._rigCameras = new Array();
  21990. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21991. /** @hidden */
  21992. _this._skipRendering = false;
  21993. _this.customRenderTargets = new Array();
  21994. // Observables
  21995. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21996. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21997. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21998. _this.onRestoreStateObservable = new BABYLON.Observable();
  21999. // Cache
  22000. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22001. _this._projectionMatrix = new BABYLON.Matrix();
  22002. _this._doNotComputeProjectionMatrix = false;
  22003. _this._worldMatrix = BABYLON.Matrix.Identity();
  22004. _this._postProcesses = new Array();
  22005. _this._transformMatrix = BABYLON.Matrix.Zero();
  22006. _this._activeMeshes = new BABYLON.SmartArray(256);
  22007. _this._globalPosition = BABYLON.Vector3.Zero();
  22008. _this._refreshFrustumPlanes = true;
  22009. _this.getScene().addCamera(_this);
  22010. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22011. _this.getScene().activeCamera = _this;
  22012. }
  22013. _this.position = position;
  22014. return _this;
  22015. }
  22016. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22017. get: function () {
  22018. return Camera._PERSPECTIVE_CAMERA;
  22019. },
  22020. enumerable: true,
  22021. configurable: true
  22022. });
  22023. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22024. get: function () {
  22025. return Camera._ORTHOGRAPHIC_CAMERA;
  22026. },
  22027. enumerable: true,
  22028. configurable: true
  22029. });
  22030. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22031. /**
  22032. * This is the default FOV mode for perspective cameras.
  22033. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22034. *
  22035. */
  22036. get: function () {
  22037. return Camera._FOVMODE_VERTICAL_FIXED;
  22038. },
  22039. enumerable: true,
  22040. configurable: true
  22041. });
  22042. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22043. /**
  22044. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22045. *
  22046. */
  22047. get: function () {
  22048. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22054. get: function () {
  22055. return Camera._RIG_MODE_NONE;
  22056. },
  22057. enumerable: true,
  22058. configurable: true
  22059. });
  22060. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22061. get: function () {
  22062. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22068. get: function () {
  22069. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22070. },
  22071. enumerable: true,
  22072. configurable: true
  22073. });
  22074. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22075. get: function () {
  22076. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22077. },
  22078. enumerable: true,
  22079. configurable: true
  22080. });
  22081. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22082. get: function () {
  22083. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22089. get: function () {
  22090. return Camera._RIG_MODE_VR;
  22091. },
  22092. enumerable: true,
  22093. configurable: true
  22094. });
  22095. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22096. get: function () {
  22097. return Camera._RIG_MODE_WEBVR;
  22098. },
  22099. enumerable: true,
  22100. configurable: true
  22101. });
  22102. /**
  22103. * Store current camera state (fov, position, etc..)
  22104. */
  22105. Camera.prototype.storeState = function () {
  22106. this._stateStored = true;
  22107. this._storedFov = this.fov;
  22108. return this;
  22109. };
  22110. /**
  22111. * Restores the camera state values if it has been stored. You must call storeState() first
  22112. */
  22113. Camera.prototype._restoreStateValues = function () {
  22114. if (!this._stateStored) {
  22115. return false;
  22116. }
  22117. this.fov = this._storedFov;
  22118. return true;
  22119. };
  22120. /**
  22121. * Restored camera state. You must call storeState() first
  22122. */
  22123. Camera.prototype.restoreState = function () {
  22124. if (this._restoreStateValues()) {
  22125. this.onRestoreStateObservable.notifyObservers(this);
  22126. return true;
  22127. }
  22128. return false;
  22129. };
  22130. Camera.prototype.getClassName = function () {
  22131. return "Camera";
  22132. };
  22133. /**
  22134. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22135. */
  22136. Camera.prototype.toString = function (fullDetails) {
  22137. var ret = "Name: " + this.name;
  22138. ret += ", type: " + this.getClassName();
  22139. if (this.animations) {
  22140. for (var i = 0; i < this.animations.length; i++) {
  22141. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22142. }
  22143. }
  22144. if (fullDetails) {
  22145. }
  22146. return ret;
  22147. };
  22148. Object.defineProperty(Camera.prototype, "globalPosition", {
  22149. get: function () {
  22150. return this._globalPosition;
  22151. },
  22152. enumerable: true,
  22153. configurable: true
  22154. });
  22155. Camera.prototype.getActiveMeshes = function () {
  22156. return this._activeMeshes;
  22157. };
  22158. Camera.prototype.isActiveMesh = function (mesh) {
  22159. return (this._activeMeshes.indexOf(mesh) !== -1);
  22160. };
  22161. /**
  22162. * Is this camera ready to be used/rendered
  22163. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22164. * @return true if the camera is ready
  22165. */
  22166. Camera.prototype.isReady = function (completeCheck) {
  22167. if (completeCheck === void 0) { completeCheck = false; }
  22168. if (completeCheck) {
  22169. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22170. var pp = _a[_i];
  22171. if (pp && !pp.isReady()) {
  22172. return false;
  22173. }
  22174. }
  22175. }
  22176. return _super.prototype.isReady.call(this, completeCheck);
  22177. };
  22178. //Cache
  22179. /** @hidden */
  22180. Camera.prototype._initCache = function () {
  22181. _super.prototype._initCache.call(this);
  22182. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22183. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22184. this._cache.mode = undefined;
  22185. this._cache.minZ = undefined;
  22186. this._cache.maxZ = undefined;
  22187. this._cache.fov = undefined;
  22188. this._cache.fovMode = undefined;
  22189. this._cache.aspectRatio = undefined;
  22190. this._cache.orthoLeft = undefined;
  22191. this._cache.orthoRight = undefined;
  22192. this._cache.orthoBottom = undefined;
  22193. this._cache.orthoTop = undefined;
  22194. this._cache.renderWidth = undefined;
  22195. this._cache.renderHeight = undefined;
  22196. };
  22197. /** @hidden */
  22198. Camera.prototype._updateCache = function (ignoreParentClass) {
  22199. if (!ignoreParentClass) {
  22200. _super.prototype._updateCache.call(this);
  22201. }
  22202. this._cache.position.copyFrom(this.position);
  22203. this._cache.upVector.copyFrom(this.upVector);
  22204. };
  22205. // Synchronized
  22206. /** @hidden */
  22207. Camera.prototype._isSynchronized = function () {
  22208. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22209. };
  22210. /** @hidden */
  22211. Camera.prototype._isSynchronizedViewMatrix = function () {
  22212. if (!_super.prototype._isSynchronized.call(this))
  22213. return false;
  22214. return this._cache.position.equals(this.position)
  22215. && this._cache.upVector.equals(this.upVector)
  22216. && this.isSynchronizedWithParent();
  22217. };
  22218. /** @hidden */
  22219. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22220. var check = this._cache.mode === this.mode
  22221. && this._cache.minZ === this.minZ
  22222. && this._cache.maxZ === this.maxZ;
  22223. if (!check) {
  22224. return false;
  22225. }
  22226. var engine = this.getEngine();
  22227. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22228. check = this._cache.fov === this.fov
  22229. && this._cache.fovMode === this.fovMode
  22230. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22231. }
  22232. else {
  22233. check = this._cache.orthoLeft === this.orthoLeft
  22234. && this._cache.orthoRight === this.orthoRight
  22235. && this._cache.orthoBottom === this.orthoBottom
  22236. && this._cache.orthoTop === this.orthoTop
  22237. && this._cache.renderWidth === engine.getRenderWidth()
  22238. && this._cache.renderHeight === engine.getRenderHeight();
  22239. }
  22240. return check;
  22241. };
  22242. // Controls
  22243. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22244. };
  22245. Camera.prototype.detachControl = function (element) {
  22246. };
  22247. Camera.prototype.update = function () {
  22248. this._checkInputs();
  22249. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22250. this._updateRigCameras();
  22251. }
  22252. };
  22253. /** @hidden */
  22254. Camera.prototype._checkInputs = function () {
  22255. this.onAfterCheckInputsObservable.notifyObservers(this);
  22256. };
  22257. Object.defineProperty(Camera.prototype, "rigCameras", {
  22258. get: function () {
  22259. return this._rigCameras;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22265. get: function () {
  22266. return this._rigPostProcess;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. /**
  22272. * Internal, gets the first post proces.
  22273. * @returns the first post process to be run on this camera.
  22274. */
  22275. Camera.prototype._getFirstPostProcess = function () {
  22276. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22277. if (this._postProcesses[ppIndex] !== null) {
  22278. return this._postProcesses[ppIndex];
  22279. }
  22280. }
  22281. return null;
  22282. };
  22283. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22284. // invalidate framebuffer
  22285. var firstPostProcess = this._getFirstPostProcess();
  22286. if (firstPostProcess) {
  22287. firstPostProcess.markTextureDirty();
  22288. }
  22289. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22290. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22291. var cam = this._rigCameras[i];
  22292. var rigPostProcess = cam._rigPostProcess;
  22293. // for VR rig, there does not have to be a post process
  22294. if (rigPostProcess) {
  22295. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22296. if (isPass) {
  22297. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22298. cam.isIntermediate = this._postProcesses.length === 0;
  22299. }
  22300. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22301. rigPostProcess.markTextureDirty();
  22302. }
  22303. else {
  22304. cam._postProcesses = this._postProcesses.slice(0);
  22305. }
  22306. }
  22307. };
  22308. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22309. if (insertAt === void 0) { insertAt = null; }
  22310. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22311. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22312. return 0;
  22313. }
  22314. if (insertAt == null || insertAt < 0) {
  22315. this._postProcesses.push(postProcess);
  22316. }
  22317. else if (this._postProcesses[insertAt] === null) {
  22318. this._postProcesses[insertAt] = postProcess;
  22319. }
  22320. else {
  22321. this._postProcesses.splice(insertAt, 0, postProcess);
  22322. }
  22323. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22324. return this._postProcesses.indexOf(postProcess);
  22325. };
  22326. Camera.prototype.detachPostProcess = function (postProcess) {
  22327. var idx = this._postProcesses.indexOf(postProcess);
  22328. if (idx !== -1) {
  22329. this._postProcesses[idx] = null;
  22330. }
  22331. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22332. };
  22333. Camera.prototype.getWorldMatrix = function () {
  22334. if (this._isSynchronizedViewMatrix()) {
  22335. return this._worldMatrix;
  22336. }
  22337. // Getting the the view matrix will also compute the world matrix.
  22338. this.getViewMatrix();
  22339. return this._worldMatrix;
  22340. };
  22341. /** @hidden */
  22342. Camera.prototype._getViewMatrix = function () {
  22343. return BABYLON.Matrix.Identity();
  22344. };
  22345. Camera.prototype.getViewMatrix = function (force) {
  22346. if (!force && this._isSynchronizedViewMatrix()) {
  22347. return this._computedViewMatrix;
  22348. }
  22349. this.updateCache();
  22350. this._computedViewMatrix = this._getViewMatrix();
  22351. this._currentRenderId = this.getScene().getRenderId();
  22352. this._childRenderId = this._currentRenderId;
  22353. this._refreshFrustumPlanes = true;
  22354. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22355. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22356. }
  22357. this.onViewMatrixChangedObservable.notifyObservers(this);
  22358. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22359. return this._computedViewMatrix;
  22360. };
  22361. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22362. this._doNotComputeProjectionMatrix = true;
  22363. if (projection !== undefined) {
  22364. this._projectionMatrix = projection;
  22365. }
  22366. };
  22367. ;
  22368. Camera.prototype.unfreezeProjectionMatrix = function () {
  22369. this._doNotComputeProjectionMatrix = false;
  22370. };
  22371. ;
  22372. Camera.prototype.getProjectionMatrix = function (force) {
  22373. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22374. return this._projectionMatrix;
  22375. }
  22376. // Cache
  22377. this._cache.mode = this.mode;
  22378. this._cache.minZ = this.minZ;
  22379. this._cache.maxZ = this.maxZ;
  22380. // Matrix
  22381. this._refreshFrustumPlanes = true;
  22382. var engine = this.getEngine();
  22383. var scene = this.getScene();
  22384. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22385. this._cache.fov = this.fov;
  22386. this._cache.fovMode = this.fovMode;
  22387. this._cache.aspectRatio = engine.getAspectRatio(this);
  22388. if (this.minZ <= 0) {
  22389. this.minZ = 0.1;
  22390. }
  22391. if (scene.useRightHandedSystem) {
  22392. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22393. }
  22394. else {
  22395. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22396. }
  22397. }
  22398. else {
  22399. var halfWidth = engine.getRenderWidth() / 2.0;
  22400. var halfHeight = engine.getRenderHeight() / 2.0;
  22401. if (scene.useRightHandedSystem) {
  22402. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22403. }
  22404. else {
  22405. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22406. }
  22407. this._cache.orthoLeft = this.orthoLeft;
  22408. this._cache.orthoRight = this.orthoRight;
  22409. this._cache.orthoBottom = this.orthoBottom;
  22410. this._cache.orthoTop = this.orthoTop;
  22411. this._cache.renderWidth = engine.getRenderWidth();
  22412. this._cache.renderHeight = engine.getRenderHeight();
  22413. }
  22414. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22415. return this._projectionMatrix;
  22416. };
  22417. /**
  22418. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22419. * @returns a Matrix
  22420. */
  22421. Camera.prototype.getTransformationMatrix = function () {
  22422. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22423. return this._transformMatrix;
  22424. };
  22425. Camera.prototype.updateFrustumPlanes = function () {
  22426. if (!this._refreshFrustumPlanes) {
  22427. return;
  22428. }
  22429. this.getTransformationMatrix();
  22430. if (!this._frustumPlanes) {
  22431. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22432. }
  22433. else {
  22434. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22435. }
  22436. this._refreshFrustumPlanes = false;
  22437. };
  22438. Camera.prototype.isInFrustum = function (target) {
  22439. this.updateFrustumPlanes();
  22440. return target.isInFrustum(this._frustumPlanes);
  22441. };
  22442. Camera.prototype.isCompletelyInFrustum = function (target) {
  22443. this.updateFrustumPlanes();
  22444. return target.isCompletelyInFrustum(this._frustumPlanes);
  22445. };
  22446. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22447. if (length === void 0) { length = 100; }
  22448. if (!transform) {
  22449. transform = this.getWorldMatrix();
  22450. }
  22451. if (!origin) {
  22452. origin = this.position;
  22453. }
  22454. var forward = new BABYLON.Vector3(0, 0, 1);
  22455. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22456. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22457. return new BABYLON.Ray(origin, direction, length);
  22458. };
  22459. /**
  22460. * Releases resources associated with this node.
  22461. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22462. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22463. */
  22464. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22465. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22466. // Observables
  22467. this.onViewMatrixChangedObservable.clear();
  22468. this.onProjectionMatrixChangedObservable.clear();
  22469. this.onAfterCheckInputsObservable.clear();
  22470. this.onRestoreStateObservable.clear();
  22471. // Inputs
  22472. if (this.inputs) {
  22473. this.inputs.clear();
  22474. }
  22475. // Animations
  22476. this.getScene().stopAnimation(this);
  22477. // Remove from scene
  22478. this.getScene().removeCamera(this);
  22479. while (this._rigCameras.length > 0) {
  22480. var camera = this._rigCameras.pop();
  22481. if (camera) {
  22482. camera.dispose();
  22483. }
  22484. }
  22485. // Postprocesses
  22486. if (this._rigPostProcess) {
  22487. this._rigPostProcess.dispose(this);
  22488. this._rigPostProcess = null;
  22489. this._postProcesses = [];
  22490. }
  22491. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22492. this._rigPostProcess = null;
  22493. this._postProcesses = [];
  22494. }
  22495. else {
  22496. var i = this._postProcesses.length;
  22497. while (--i >= 0) {
  22498. var postProcess = this._postProcesses[i];
  22499. if (postProcess) {
  22500. postProcess.dispose(this);
  22501. }
  22502. }
  22503. }
  22504. // Render targets
  22505. var i = this.customRenderTargets.length;
  22506. while (--i >= 0) {
  22507. this.customRenderTargets[i].dispose();
  22508. }
  22509. this.customRenderTargets = [];
  22510. // Active Meshes
  22511. this._activeMeshes.dispose();
  22512. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22513. };
  22514. Object.defineProperty(Camera.prototype, "leftCamera", {
  22515. // ---- Camera rigs section ----
  22516. get: function () {
  22517. if (this._rigCameras.length < 1) {
  22518. return null;
  22519. }
  22520. return this._rigCameras[0];
  22521. },
  22522. enumerable: true,
  22523. configurable: true
  22524. });
  22525. Object.defineProperty(Camera.prototype, "rightCamera", {
  22526. get: function () {
  22527. if (this._rigCameras.length < 2) {
  22528. return null;
  22529. }
  22530. return this._rigCameras[1];
  22531. },
  22532. enumerable: true,
  22533. configurable: true
  22534. });
  22535. Camera.prototype.getLeftTarget = function () {
  22536. if (this._rigCameras.length < 1) {
  22537. return null;
  22538. }
  22539. return this._rigCameras[0].getTarget();
  22540. };
  22541. Camera.prototype.getRightTarget = function () {
  22542. if (this._rigCameras.length < 2) {
  22543. return null;
  22544. }
  22545. return this._rigCameras[1].getTarget();
  22546. };
  22547. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22548. if (this.cameraRigMode === mode) {
  22549. return;
  22550. }
  22551. while (this._rigCameras.length > 0) {
  22552. var camera = this._rigCameras.pop();
  22553. if (camera) {
  22554. camera.dispose();
  22555. }
  22556. }
  22557. this.cameraRigMode = mode;
  22558. this._cameraRigParams = {};
  22559. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22560. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22561. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22562. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22563. // create the rig cameras, unless none
  22564. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22565. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22566. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22567. if (leftCamera && rightCamera) {
  22568. this._rigCameras.push(leftCamera);
  22569. this._rigCameras.push(rightCamera);
  22570. }
  22571. }
  22572. switch (this.cameraRigMode) {
  22573. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22574. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22575. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22576. break;
  22577. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22578. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22579. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22580. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22581. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22582. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22583. break;
  22584. case Camera.RIG_MODE_VR:
  22585. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22586. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22587. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22588. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22589. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22590. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22591. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22592. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22593. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22594. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22595. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22596. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22597. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22598. if (metrics.compensateDistortion) {
  22599. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22600. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22601. }
  22602. break;
  22603. case Camera.RIG_MODE_WEBVR:
  22604. if (rigParams.vrDisplay) {
  22605. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22606. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22607. //Left eye
  22608. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22609. this._rigCameras[0].setCameraRigParameter("left", true);
  22610. //leaving this for future reference
  22611. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22612. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22613. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22614. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22615. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22616. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22617. this._rigCameras[0].parent = this;
  22618. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22619. //Right eye
  22620. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22621. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22622. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22623. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22624. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22625. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22626. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22627. this._rigCameras[1].parent = this;
  22628. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22629. if (Camera.UseAlternateWebVRRendering) {
  22630. this._rigCameras[1]._skipRendering = true;
  22631. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22632. }
  22633. }
  22634. break;
  22635. }
  22636. this._cascadePostProcessesToRigCams();
  22637. this.update();
  22638. };
  22639. Camera.prototype._getVRProjectionMatrix = function () {
  22640. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22641. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22642. return this._projectionMatrix;
  22643. };
  22644. Camera.prototype._updateCameraRotationMatrix = function () {
  22645. //Here for WebVR
  22646. };
  22647. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22648. //Here for WebVR
  22649. };
  22650. /**
  22651. * This function MUST be overwritten by the different WebVR cameras available.
  22652. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22653. */
  22654. Camera.prototype._getWebVRProjectionMatrix = function () {
  22655. return BABYLON.Matrix.Identity();
  22656. };
  22657. /**
  22658. * This function MUST be overwritten by the different WebVR cameras available.
  22659. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22660. */
  22661. Camera.prototype._getWebVRViewMatrix = function () {
  22662. return BABYLON.Matrix.Identity();
  22663. };
  22664. Camera.prototype.setCameraRigParameter = function (name, value) {
  22665. if (!this._cameraRigParams) {
  22666. this._cameraRigParams = {};
  22667. }
  22668. this._cameraRigParams[name] = value;
  22669. //provisionnally:
  22670. if (name === "interaxialDistance") {
  22671. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22672. }
  22673. };
  22674. /**
  22675. * needs to be overridden by children so sub has required properties to be copied
  22676. */
  22677. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22678. return null;
  22679. };
  22680. /**
  22681. * May need to be overridden by children
  22682. * @hidden
  22683. */
  22684. Camera.prototype._updateRigCameras = function () {
  22685. for (var i = 0; i < this._rigCameras.length; i++) {
  22686. this._rigCameras[i].minZ = this.minZ;
  22687. this._rigCameras[i].maxZ = this.maxZ;
  22688. this._rigCameras[i].fov = this.fov;
  22689. }
  22690. // only update viewport when ANAGLYPH
  22691. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22692. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22693. }
  22694. };
  22695. /** @hidden */
  22696. Camera.prototype._setupInputs = function () {
  22697. };
  22698. Camera.prototype.serialize = function () {
  22699. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22700. // Type
  22701. serializationObject.type = this.getClassName();
  22702. // Parent
  22703. if (this.parent) {
  22704. serializationObject.parentId = this.parent.id;
  22705. }
  22706. if (this.inputs) {
  22707. this.inputs.serialize(serializationObject);
  22708. }
  22709. // Animations
  22710. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22711. serializationObject.ranges = this.serializeAnimationRanges();
  22712. return serializationObject;
  22713. };
  22714. Camera.prototype.clone = function (name) {
  22715. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22716. };
  22717. Camera.prototype.getDirection = function (localAxis) {
  22718. var result = BABYLON.Vector3.Zero();
  22719. this.getDirectionToRef(localAxis, result);
  22720. return result;
  22721. };
  22722. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22723. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22724. };
  22725. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22726. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22727. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22728. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22729. interaxial_distance: interaxial_distance,
  22730. isStereoscopicSideBySide: isStereoscopicSideBySide
  22731. });
  22732. if (constructorFunc) {
  22733. return constructorFunc;
  22734. }
  22735. // Default to universal camera
  22736. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22737. };
  22738. Camera.prototype.computeWorldMatrix = function () {
  22739. return this.getWorldMatrix();
  22740. };
  22741. Camera.Parse = function (parsedCamera, scene) {
  22742. var type = parsedCamera.type;
  22743. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22744. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22745. // Parent
  22746. if (parsedCamera.parentId) {
  22747. camera._waitingParentId = parsedCamera.parentId;
  22748. }
  22749. //If camera has an input manager, let it parse inputs settings
  22750. if (camera.inputs) {
  22751. camera.inputs.parse(parsedCamera);
  22752. camera._setupInputs();
  22753. }
  22754. if (camera.setPosition) { // need to force position
  22755. camera.position.copyFromFloats(0, 0, 0);
  22756. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22757. }
  22758. // Target
  22759. if (parsedCamera.target) {
  22760. if (camera.setTarget) {
  22761. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22762. }
  22763. }
  22764. // Apply 3d rig, when found
  22765. if (parsedCamera.cameraRigMode) {
  22766. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22767. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22768. }
  22769. // Animations
  22770. if (parsedCamera.animations) {
  22771. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22772. var parsedAnimation = parsedCamera.animations[animationIndex];
  22773. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22774. }
  22775. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22776. }
  22777. if (parsedCamera.autoAnimate) {
  22778. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22779. }
  22780. return camera;
  22781. };
  22782. // Statics
  22783. Camera._PERSPECTIVE_CAMERA = 0;
  22784. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22785. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22786. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22787. Camera._RIG_MODE_NONE = 0;
  22788. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22789. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22790. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22791. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22792. Camera._RIG_MODE_VR = 20;
  22793. Camera._RIG_MODE_WEBVR = 21;
  22794. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22795. Camera.UseAlternateWebVRRendering = false;
  22796. __decorate([
  22797. BABYLON.serializeAsVector3()
  22798. ], Camera.prototype, "position", void 0);
  22799. __decorate([
  22800. BABYLON.serializeAsVector3()
  22801. ], Camera.prototype, "upVector", void 0);
  22802. __decorate([
  22803. BABYLON.serialize()
  22804. ], Camera.prototype, "orthoLeft", void 0);
  22805. __decorate([
  22806. BABYLON.serialize()
  22807. ], Camera.prototype, "orthoRight", void 0);
  22808. __decorate([
  22809. BABYLON.serialize()
  22810. ], Camera.prototype, "orthoBottom", void 0);
  22811. __decorate([
  22812. BABYLON.serialize()
  22813. ], Camera.prototype, "orthoTop", void 0);
  22814. __decorate([
  22815. BABYLON.serialize()
  22816. ], Camera.prototype, "fov", void 0);
  22817. __decorate([
  22818. BABYLON.serialize()
  22819. ], Camera.prototype, "minZ", void 0);
  22820. __decorate([
  22821. BABYLON.serialize()
  22822. ], Camera.prototype, "maxZ", void 0);
  22823. __decorate([
  22824. BABYLON.serialize()
  22825. ], Camera.prototype, "inertia", void 0);
  22826. __decorate([
  22827. BABYLON.serialize()
  22828. ], Camera.prototype, "mode", void 0);
  22829. __decorate([
  22830. BABYLON.serialize()
  22831. ], Camera.prototype, "layerMask", void 0);
  22832. __decorate([
  22833. BABYLON.serialize()
  22834. ], Camera.prototype, "fovMode", void 0);
  22835. __decorate([
  22836. BABYLON.serialize()
  22837. ], Camera.prototype, "cameraRigMode", void 0);
  22838. __decorate([
  22839. BABYLON.serialize()
  22840. ], Camera.prototype, "interaxialDistance", void 0);
  22841. __decorate([
  22842. BABYLON.serialize()
  22843. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22844. return Camera;
  22845. }(BABYLON.Node));
  22846. BABYLON.Camera = Camera;
  22847. })(BABYLON || (BABYLON = {}));
  22848. //# sourceMappingURL=babylon.camera.js.map
  22849. var BABYLON;
  22850. (function (BABYLON) {
  22851. var RenderingManager = /** @class */ (function () {
  22852. function RenderingManager(scene) {
  22853. /**
  22854. * @hidden
  22855. */
  22856. this._useSceneAutoClearSetup = false;
  22857. this._renderingGroups = new Array();
  22858. this._autoClearDepthStencil = {};
  22859. this._customOpaqueSortCompareFn = {};
  22860. this._customAlphaTestSortCompareFn = {};
  22861. this._customTransparentSortCompareFn = {};
  22862. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  22863. this._scene = scene;
  22864. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22865. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22866. }
  22867. }
  22868. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22869. if (depth === void 0) { depth = true; }
  22870. if (stencil === void 0) { stencil = true; }
  22871. if (this._depthStencilBufferAlreadyCleaned) {
  22872. return;
  22873. }
  22874. this._scene.getEngine().clear(null, false, depth, stencil);
  22875. this._depthStencilBufferAlreadyCleaned = true;
  22876. };
  22877. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22878. // Update the observable context (not null as it only goes away on dispose)
  22879. var info = this._renderingGroupInfo;
  22880. info.scene = this._scene;
  22881. info.camera = this._scene.activeCamera;
  22882. // Dispatch sprites
  22883. if (renderSprites) {
  22884. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22885. var manager = this._scene.spriteManagers[index];
  22886. this.dispatchSprites(manager);
  22887. }
  22888. }
  22889. // Render
  22890. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22891. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22892. var renderingGroup = this._renderingGroups[index];
  22893. if (!renderingGroup)
  22894. continue;
  22895. var renderingGroupMask = Math.pow(2, index);
  22896. info.renderingGroupId = index;
  22897. // Before Observable
  22898. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22899. // Clear depth/stencil if needed
  22900. if (RenderingManager.AUTOCLEAR) {
  22901. var autoClear = this._useSceneAutoClearSetup ?
  22902. this._scene.getAutoClearDepthStencilSetup(index) :
  22903. this._autoClearDepthStencil[index];
  22904. if (autoClear && autoClear.autoClear) {
  22905. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22906. }
  22907. }
  22908. // Render
  22909. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22910. var step = _a[_i];
  22911. step.action(index);
  22912. }
  22913. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22914. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22915. var step = _c[_b];
  22916. step.action(index);
  22917. }
  22918. // After Observable
  22919. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22920. }
  22921. };
  22922. RenderingManager.prototype.reset = function () {
  22923. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22924. var renderingGroup = this._renderingGroups[index];
  22925. if (renderingGroup) {
  22926. renderingGroup.prepare();
  22927. }
  22928. }
  22929. };
  22930. RenderingManager.prototype.dispose = function () {
  22931. this.freeRenderingGroups();
  22932. this._renderingGroups.length = 0;
  22933. this._renderingGroupInfo = null;
  22934. };
  22935. /**
  22936. * Clear the info related to rendering groups preventing retention points during dispose.
  22937. */
  22938. RenderingManager.prototype.freeRenderingGroups = function () {
  22939. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22940. var renderingGroup = this._renderingGroups[index];
  22941. if (renderingGroup) {
  22942. renderingGroup.dispose();
  22943. }
  22944. }
  22945. };
  22946. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22947. if (this._renderingGroups[renderingGroupId] === undefined) {
  22948. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22949. }
  22950. };
  22951. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22952. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22953. this._prepareRenderingGroup(renderingGroupId);
  22954. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22955. };
  22956. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22957. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22958. this._prepareRenderingGroup(renderingGroupId);
  22959. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22960. };
  22961. /**
  22962. * @param subMesh The submesh to dispatch
  22963. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22964. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22965. */
  22966. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22967. if (mesh === undefined) {
  22968. mesh = subMesh.getMesh();
  22969. }
  22970. var renderingGroupId = mesh.renderingGroupId || 0;
  22971. this._prepareRenderingGroup(renderingGroupId);
  22972. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22973. };
  22974. /**
  22975. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22976. * This allowed control for front to back rendering or reversly depending of the special needs.
  22977. *
  22978. * @param renderingGroupId The rendering group id corresponding to its index
  22979. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22980. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22981. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22982. */
  22983. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22984. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22985. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22986. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22987. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22988. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22989. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22990. if (this._renderingGroups[renderingGroupId]) {
  22991. var group = this._renderingGroups[renderingGroupId];
  22992. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22993. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22994. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22995. }
  22996. };
  22997. /**
  22998. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22999. *
  23000. * @param renderingGroupId The rendering group id corresponding to its index
  23001. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23002. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23003. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23004. */
  23005. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23006. if (depth === void 0) { depth = true; }
  23007. if (stencil === void 0) { stencil = true; }
  23008. this._autoClearDepthStencil[renderingGroupId] = {
  23009. autoClear: autoClearDepthStencil,
  23010. depth: depth,
  23011. stencil: stencil
  23012. };
  23013. };
  23014. /**
  23015. * Gets the current auto clear configuration for one rendering group of the rendering
  23016. * manager.
  23017. * @param index the rendering group index to get the information for
  23018. * @returns The auto clear setup for the requested rendering group
  23019. */
  23020. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23021. return this._autoClearDepthStencil[index];
  23022. };
  23023. /**
  23024. * The max id used for rendering groups (not included)
  23025. */
  23026. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23027. /**
  23028. * The min id used for rendering groups (included)
  23029. */
  23030. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23031. /**
  23032. * Used to globally prevent autoclearing scenes.
  23033. */
  23034. RenderingManager.AUTOCLEAR = true;
  23035. return RenderingManager;
  23036. }());
  23037. BABYLON.RenderingManager = RenderingManager;
  23038. })(BABYLON || (BABYLON = {}));
  23039. //# sourceMappingURL=babylon.renderingManager.js.map
  23040. var BABYLON;
  23041. (function (BABYLON) {
  23042. var RenderingGroup = /** @class */ (function () {
  23043. /**
  23044. * Creates a new rendering group.
  23045. * @param index The rendering group index
  23046. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23047. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23048. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23049. */
  23050. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23051. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23052. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23053. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23054. this.index = index;
  23055. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23056. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23057. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23058. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23059. this._particleSystems = new BABYLON.SmartArray(256);
  23060. this._spriteManagers = new BABYLON.SmartArray(256);
  23061. this._edgesRenderers = new BABYLON.SmartArray(16);
  23062. this._scene = scene;
  23063. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23064. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23065. this.transparentSortCompareFn = transparentSortCompareFn;
  23066. }
  23067. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23068. /**
  23069. * Set the opaque sort comparison function.
  23070. * If null the sub meshes will be render in the order they were created
  23071. */
  23072. set: function (value) {
  23073. this._opaqueSortCompareFn = value;
  23074. if (value) {
  23075. this._renderOpaque = this.renderOpaqueSorted;
  23076. }
  23077. else {
  23078. this._renderOpaque = RenderingGroup.renderUnsorted;
  23079. }
  23080. },
  23081. enumerable: true,
  23082. configurable: true
  23083. });
  23084. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23085. /**
  23086. * Set the alpha test sort comparison function.
  23087. * If null the sub meshes will be render in the order they were created
  23088. */
  23089. set: function (value) {
  23090. this._alphaTestSortCompareFn = value;
  23091. if (value) {
  23092. this._renderAlphaTest = this.renderAlphaTestSorted;
  23093. }
  23094. else {
  23095. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23096. }
  23097. },
  23098. enumerable: true,
  23099. configurable: true
  23100. });
  23101. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23102. /**
  23103. * Set the transparent sort comparison function.
  23104. * If null the sub meshes will be render in the order they were created
  23105. */
  23106. set: function (value) {
  23107. if (value) {
  23108. this._transparentSortCompareFn = value;
  23109. }
  23110. else {
  23111. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23112. }
  23113. this._renderTransparent = this.renderTransparentSorted;
  23114. },
  23115. enumerable: true,
  23116. configurable: true
  23117. });
  23118. /**
  23119. * Render all the sub meshes contained in the group.
  23120. * @param customRenderFunction Used to override the default render behaviour of the group.
  23121. * @returns true if rendered some submeshes.
  23122. */
  23123. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23124. if (customRenderFunction) {
  23125. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23126. return;
  23127. }
  23128. var engine = this._scene.getEngine();
  23129. // Depth only
  23130. if (this._depthOnlySubMeshes.length !== 0) {
  23131. engine.setColorWrite(false);
  23132. this._renderAlphaTest(this._depthOnlySubMeshes);
  23133. engine.setColorWrite(true);
  23134. }
  23135. // Opaque
  23136. if (this._opaqueSubMeshes.length !== 0) {
  23137. this._renderOpaque(this._opaqueSubMeshes);
  23138. }
  23139. // Alpha test
  23140. if (this._alphaTestSubMeshes.length !== 0) {
  23141. this._renderAlphaTest(this._alphaTestSubMeshes);
  23142. }
  23143. var stencilState = engine.getStencilBuffer();
  23144. engine.setStencilBuffer(false);
  23145. // Sprites
  23146. if (renderSprites) {
  23147. this._renderSprites();
  23148. }
  23149. // Particles
  23150. if (renderParticles) {
  23151. this._renderParticles(activeMeshes);
  23152. }
  23153. if (this.onBeforeTransparentRendering) {
  23154. this.onBeforeTransparentRendering();
  23155. }
  23156. // Transparent
  23157. if (this._transparentSubMeshes.length !== 0) {
  23158. this._renderTransparent(this._transparentSubMeshes);
  23159. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23160. }
  23161. // Set back stencil to false in case it changes before the edge renderer.
  23162. engine.setStencilBuffer(false);
  23163. // Edges
  23164. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23165. this._edgesRenderers.data[edgesRendererIndex].render();
  23166. }
  23167. // Restore Stencil state.
  23168. engine.setStencilBuffer(stencilState);
  23169. };
  23170. /**
  23171. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23172. * @param subMeshes The submeshes to render
  23173. */
  23174. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23175. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23176. };
  23177. /**
  23178. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23179. * @param subMeshes The submeshes to render
  23180. */
  23181. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23182. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23183. };
  23184. /**
  23185. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23186. * @param subMeshes The submeshes to render
  23187. */
  23188. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23189. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23190. };
  23191. /**
  23192. * Renders the submeshes in a specified order.
  23193. * @param subMeshes The submeshes to sort before render
  23194. * @param sortCompareFn The comparison function use to sort
  23195. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23196. * @param transparent Specifies to activate blending if true
  23197. */
  23198. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23199. var subIndex = 0;
  23200. var subMesh;
  23201. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23202. for (; subIndex < subMeshes.length; subIndex++) {
  23203. subMesh = subMeshes.data[subIndex];
  23204. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23205. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23206. }
  23207. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23208. if (sortCompareFn) {
  23209. sortedArray.sort(sortCompareFn);
  23210. }
  23211. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23212. subMesh = sortedArray[subIndex];
  23213. if (transparent) {
  23214. var material = subMesh.getMaterial();
  23215. if (material && material.needDepthPrePass) {
  23216. var engine = material.getScene().getEngine();
  23217. engine.setColorWrite(false);
  23218. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23219. subMesh.render(false);
  23220. engine.setColorWrite(true);
  23221. }
  23222. }
  23223. subMesh.render(transparent);
  23224. }
  23225. };
  23226. /**
  23227. * Renders the submeshes in the order they were dispatched (no sort applied).
  23228. * @param subMeshes The submeshes to render
  23229. */
  23230. RenderingGroup.renderUnsorted = function (subMeshes) {
  23231. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23232. var submesh = subMeshes.data[subIndex];
  23233. submesh.render(false);
  23234. }
  23235. };
  23236. /**
  23237. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23238. * are rendered back to front if in the same alpha index.
  23239. *
  23240. * @param a The first submesh
  23241. * @param b The second submesh
  23242. * @returns The result of the comparison
  23243. */
  23244. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23245. // Alpha index first
  23246. if (a._alphaIndex > b._alphaIndex) {
  23247. return 1;
  23248. }
  23249. if (a._alphaIndex < b._alphaIndex) {
  23250. return -1;
  23251. }
  23252. // Then distance to camera
  23253. return RenderingGroup.backToFrontSortCompare(a, b);
  23254. };
  23255. /**
  23256. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23257. * are rendered back to front.
  23258. *
  23259. * @param a The first submesh
  23260. * @param b The second submesh
  23261. * @returns The result of the comparison
  23262. */
  23263. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23264. // Then distance to camera
  23265. if (a._distanceToCamera < b._distanceToCamera) {
  23266. return 1;
  23267. }
  23268. if (a._distanceToCamera > b._distanceToCamera) {
  23269. return -1;
  23270. }
  23271. return 0;
  23272. };
  23273. /**
  23274. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23275. * are rendered front to back (prevent overdraw).
  23276. *
  23277. * @param a The first submesh
  23278. * @param b The second submesh
  23279. * @returns The result of the comparison
  23280. */
  23281. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23282. // Then distance to camera
  23283. if (a._distanceToCamera < b._distanceToCamera) {
  23284. return -1;
  23285. }
  23286. if (a._distanceToCamera > b._distanceToCamera) {
  23287. return 1;
  23288. }
  23289. return 0;
  23290. };
  23291. /**
  23292. * Resets the different lists of submeshes to prepare a new frame.
  23293. */
  23294. RenderingGroup.prototype.prepare = function () {
  23295. this._opaqueSubMeshes.reset();
  23296. this._transparentSubMeshes.reset();
  23297. this._alphaTestSubMeshes.reset();
  23298. this._depthOnlySubMeshes.reset();
  23299. this._particleSystems.reset();
  23300. this._spriteManagers.reset();
  23301. this._edgesRenderers.reset();
  23302. };
  23303. RenderingGroup.prototype.dispose = function () {
  23304. this._opaqueSubMeshes.dispose();
  23305. this._transparentSubMeshes.dispose();
  23306. this._alphaTestSubMeshes.dispose();
  23307. this._depthOnlySubMeshes.dispose();
  23308. this._particleSystems.dispose();
  23309. this._spriteManagers.dispose();
  23310. this._edgesRenderers.dispose();
  23311. };
  23312. /**
  23313. * Inserts the submesh in its correct queue depending on its material.
  23314. * @param subMesh The submesh to dispatch
  23315. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23316. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23317. */
  23318. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23319. // Get mesh and materials if not provided
  23320. if (mesh === undefined) {
  23321. mesh = subMesh.getMesh();
  23322. }
  23323. if (material === undefined) {
  23324. material = subMesh.getMaterial();
  23325. }
  23326. if (material === null || material === undefined) {
  23327. return;
  23328. }
  23329. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23330. this._transparentSubMeshes.push(subMesh);
  23331. }
  23332. else if (material.needAlphaTesting()) { // Alpha test
  23333. if (material.needDepthPrePass) {
  23334. this._depthOnlySubMeshes.push(subMesh);
  23335. }
  23336. this._alphaTestSubMeshes.push(subMesh);
  23337. }
  23338. else {
  23339. if (material.needDepthPrePass) {
  23340. this._depthOnlySubMeshes.push(subMesh);
  23341. }
  23342. this._opaqueSubMeshes.push(subMesh); // Opaque
  23343. }
  23344. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23345. this._edgesRenderers.push(mesh._edgesRenderer);
  23346. }
  23347. };
  23348. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23349. this._spriteManagers.push(spriteManager);
  23350. };
  23351. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23352. this._particleSystems.push(particleSystem);
  23353. };
  23354. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23355. if (this._particleSystems.length === 0) {
  23356. return;
  23357. }
  23358. // Particles
  23359. var activeCamera = this._scene.activeCamera;
  23360. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23361. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23362. var particleSystem = this._particleSystems.data[particleIndex];
  23363. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23364. continue;
  23365. }
  23366. var emitter = particleSystem.emitter;
  23367. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23368. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23369. }
  23370. }
  23371. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23372. };
  23373. RenderingGroup.prototype._renderSprites = function () {
  23374. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23375. return;
  23376. }
  23377. // Sprites
  23378. var activeCamera = this._scene.activeCamera;
  23379. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23380. for (var id = 0; id < this._spriteManagers.length; id++) {
  23381. var spriteManager = this._spriteManagers.data[id];
  23382. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23383. spriteManager.render();
  23384. }
  23385. }
  23386. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23387. };
  23388. return RenderingGroup;
  23389. }());
  23390. BABYLON.RenderingGroup = RenderingGroup;
  23391. })(BABYLON || (BABYLON = {}));
  23392. //# sourceMappingURL=babylon.renderingGroup.js.map
  23393. var BABYLON;
  23394. (function (BABYLON) {
  23395. /**
  23396. * Groups all the scene component constants in one place to ease maintenance.
  23397. * @hidden
  23398. */
  23399. var SceneComponentConstants = /** @class */ (function () {
  23400. function SceneComponentConstants() {
  23401. }
  23402. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23403. SceneComponentConstants.NAME_LAYER = "Layer";
  23404. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23405. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23406. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23407. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23408. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23409. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23410. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23411. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23412. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23413. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23414. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23415. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23416. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23417. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23418. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23419. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23420. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23421. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23422. return SceneComponentConstants;
  23423. }());
  23424. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23425. /**
  23426. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23427. * @hidden
  23428. */
  23429. var Stage = /** @class */ (function (_super) {
  23430. __extends(Stage, _super);
  23431. /**
  23432. * Hide ctor from the rest of the world.
  23433. * @param items The items to add.
  23434. */
  23435. function Stage(items) {
  23436. return _super.apply(this, items) || this;
  23437. }
  23438. /**
  23439. * Creates a new Stage.
  23440. * @returns A new instance of a Stage
  23441. */
  23442. Stage.Create = function () {
  23443. return Object.create(Stage.prototype);
  23444. };
  23445. /**
  23446. * Registers a step in an ordered way in the targeted stage.
  23447. * @param index Defines the position to register the step in
  23448. * @param component Defines the component attached to the step
  23449. * @param action Defines the action to launch during the step
  23450. */
  23451. Stage.prototype.registerStep = function (index, component, action) {
  23452. var i = 0;
  23453. var maxIndex = Number.MAX_VALUE;
  23454. for (; i < this.length && i < maxIndex; i++) {
  23455. var step = this[i];
  23456. maxIndex = step.index;
  23457. }
  23458. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23459. };
  23460. /**
  23461. * Clears all the steps from the stage.
  23462. */
  23463. Stage.prototype.clear = function () {
  23464. this.length = 0;
  23465. };
  23466. return Stage;
  23467. }(Array));
  23468. BABYLON.Stage = Stage;
  23469. })(BABYLON || (BABYLON = {}));
  23470. //# sourceMappingURL=babylon.sceneComponent.js.map
  23471. var BABYLON;
  23472. (function (BABYLON) {
  23473. /**
  23474. * Base class of the scene acting as a container for the different elements composing a scene.
  23475. * This class is dynamically extended by the different components of the scene increasing
  23476. * flexibility and reducing coupling
  23477. */
  23478. var AbstractScene = /** @class */ (function () {
  23479. function AbstractScene() {
  23480. /** All of the cameras added to this scene
  23481. * @see http://doc.babylonjs.com/babylon101/cameras
  23482. */
  23483. this.cameras = new Array();
  23484. /**
  23485. * All of the lights added to this scene
  23486. * @see http://doc.babylonjs.com/babylon101/lights
  23487. */
  23488. this.lights = new Array();
  23489. /**
  23490. * All of the (abstract) meshes added to this scene
  23491. */
  23492. this.meshes = new Array();
  23493. /**
  23494. * The list of skeletons added to the scene
  23495. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23496. */
  23497. this.skeletons = new Array();
  23498. /**
  23499. * All of the particle systems added to this scene
  23500. * @see http://doc.babylonjs.com/babylon101/particles
  23501. */
  23502. this.particleSystems = new Array();
  23503. /**
  23504. * Gets a list of Animations associated with the scene
  23505. */
  23506. this.animations = [];
  23507. /**
  23508. * All of the animation groups added to this scene
  23509. * @see http://doc.babylonjs.com/how_to/group
  23510. */
  23511. this.animationGroups = new Array();
  23512. /**
  23513. * All of the multi-materials added to this scene
  23514. * @see http://doc.babylonjs.com/how_to/multi_materials
  23515. */
  23516. this.multiMaterials = new Array();
  23517. /**
  23518. * All of the materials added to this scene
  23519. * @see http://doc.babylonjs.com/babylon101/materials
  23520. */
  23521. this.materials = new Array();
  23522. /**
  23523. * The list of morph target managers added to the scene
  23524. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23525. */
  23526. this.morphTargetManagers = new Array();
  23527. /**
  23528. * The list of geometries used in the scene.
  23529. */
  23530. this.geometries = new Array();
  23531. /**
  23532. * All of the tranform nodes added to this scene
  23533. * @see http://doc.babylonjs.com/how_to/transformnode
  23534. */
  23535. this.transformNodes = new Array();
  23536. /**
  23537. * ActionManagers available on the scene.
  23538. */
  23539. this.actionManagers = new Array();
  23540. /**
  23541. * Sounds to keep.
  23542. */
  23543. this.sounds = new Array();
  23544. /**
  23545. * Textures to keep.
  23546. */
  23547. this.textures = new Array();
  23548. }
  23549. /**
  23550. * Adds a parser in the list of available ones
  23551. * @param name Defines the name of the parser
  23552. * @param parser Defines the parser to add
  23553. */
  23554. AbstractScene.AddParser = function (name, parser) {
  23555. this._BabylonFileParsers[name] = parser;
  23556. };
  23557. /**
  23558. * Gets a general parser from the list of avaialble ones
  23559. * @param name Defines the name of the parser
  23560. * @returns the requested parser or null
  23561. */
  23562. AbstractScene.GetParser = function (name) {
  23563. if (this._BabylonFileParsers[name]) {
  23564. return this._BabylonFileParsers[name];
  23565. }
  23566. return null;
  23567. };
  23568. /**
  23569. * Adds n individual parser in the list of available ones
  23570. * @param name Defines the name of the parser
  23571. * @param parser Defines the parser to add
  23572. */
  23573. AbstractScene.AddIndividualParser = function (name, parser) {
  23574. this._IndividualBabylonFileParsers[name] = parser;
  23575. };
  23576. /**
  23577. * Gets an individual parser from the list of avaialble ones
  23578. * @param name Defines the name of the parser
  23579. * @returns the requested parser or null
  23580. */
  23581. AbstractScene.GetIndividualParser = function (name) {
  23582. if (this._IndividualBabylonFileParsers[name]) {
  23583. return this._IndividualBabylonFileParsers[name];
  23584. }
  23585. return null;
  23586. };
  23587. /**
  23588. * Parser json data and populate both a scene and its associated container object
  23589. * @param jsonData Defines the data to parse
  23590. * @param scene Defines the scene to parse the data for
  23591. * @param container Defines the container attached to the parsing sequence
  23592. * @param rootUrl Defines the root url of the data
  23593. */
  23594. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23595. for (var parserName in this._BabylonFileParsers) {
  23596. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23597. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23598. }
  23599. }
  23600. };
  23601. /**
  23602. * Stores the list of available parsers in the application.
  23603. */
  23604. AbstractScene._BabylonFileParsers = {};
  23605. /**
  23606. * Stores the list of available individual parsers in the application.
  23607. */
  23608. AbstractScene._IndividualBabylonFileParsers = {};
  23609. return AbstractScene;
  23610. }());
  23611. BABYLON.AbstractScene = AbstractScene;
  23612. })(BABYLON || (BABYLON = {}));
  23613. //# sourceMappingURL=babylon.abstractScene.js.map
  23614. var BABYLON;
  23615. (function (BABYLON) {
  23616. /** @hidden */
  23617. var ClickInfo = /** @class */ (function () {
  23618. function ClickInfo() {
  23619. this._singleClick = false;
  23620. this._doubleClick = false;
  23621. this._hasSwiped = false;
  23622. this._ignore = false;
  23623. }
  23624. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23625. get: function () {
  23626. return this._singleClick;
  23627. },
  23628. set: function (b) {
  23629. this._singleClick = b;
  23630. },
  23631. enumerable: true,
  23632. configurable: true
  23633. });
  23634. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23635. get: function () {
  23636. return this._doubleClick;
  23637. },
  23638. set: function (b) {
  23639. this._doubleClick = b;
  23640. },
  23641. enumerable: true,
  23642. configurable: true
  23643. });
  23644. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23645. get: function () {
  23646. return this._hasSwiped;
  23647. },
  23648. set: function (b) {
  23649. this._hasSwiped = b;
  23650. },
  23651. enumerable: true,
  23652. configurable: true
  23653. });
  23654. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23655. get: function () {
  23656. return this._ignore;
  23657. },
  23658. set: function (b) {
  23659. this._ignore = b;
  23660. },
  23661. enumerable: true,
  23662. configurable: true
  23663. });
  23664. return ClickInfo;
  23665. }());
  23666. /**
  23667. * This class is used by the onRenderingGroupObservable
  23668. */
  23669. var RenderingGroupInfo = /** @class */ (function () {
  23670. function RenderingGroupInfo() {
  23671. }
  23672. return RenderingGroupInfo;
  23673. }());
  23674. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23675. /**
  23676. * Represents a scene to be rendered by the engine.
  23677. * @see http://doc.babylonjs.com/features/scene
  23678. */
  23679. var Scene = /** @class */ (function (_super) {
  23680. __extends(Scene, _super);
  23681. /**
  23682. * Creates a new Scene
  23683. * @param engine defines the engine to use to render this scene
  23684. */
  23685. function Scene(engine) {
  23686. var _this = _super.call(this) || this;
  23687. // Members
  23688. /**
  23689. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23690. */
  23691. _this.autoClear = true;
  23692. /**
  23693. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23694. */
  23695. _this.autoClearDepthAndStencil = true;
  23696. /**
  23697. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23698. */
  23699. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23700. /**
  23701. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23702. */
  23703. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23704. _this._forceWireframe = false;
  23705. _this._forcePointsCloud = false;
  23706. /**
  23707. * Gets or sets a boolean indicating if animations are enabled
  23708. */
  23709. _this.animationsEnabled = true;
  23710. _this._animationPropertiesOverride = null;
  23711. /**
  23712. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23713. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23714. */
  23715. _this.useConstantAnimationDeltaTime = false;
  23716. /**
  23717. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23718. * Please note that it requires to run a ray cast through the scene on every frame
  23719. */
  23720. _this.constantlyUpdateMeshUnderPointer = false;
  23721. /**
  23722. * Defines the HTML cursor to use when hovering over interactive elements
  23723. */
  23724. _this.hoverCursor = "pointer";
  23725. /**
  23726. * Defines the HTML default cursor to use (empty by default)
  23727. */
  23728. _this.defaultCursor = "";
  23729. /**
  23730. * This is used to call preventDefault() on pointer down
  23731. * in order to block unwanted artifacts like system double clicks
  23732. */
  23733. _this.preventDefaultOnPointerDown = true;
  23734. // Metadata
  23735. /**
  23736. * Gets or sets user defined metadata
  23737. */
  23738. _this.metadata = null;
  23739. /**
  23740. * Use this array to add regular expressions used to disable offline support for specific urls
  23741. */
  23742. _this.disableOfflineSupportExceptionRules = new Array();
  23743. /**
  23744. * An event triggered when the scene is disposed.
  23745. */
  23746. _this.onDisposeObservable = new BABYLON.Observable();
  23747. _this._onDisposeObserver = null;
  23748. /**
  23749. * An event triggered before rendering the scene (right after animations and physics)
  23750. */
  23751. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23752. _this._onBeforeRenderObserver = null;
  23753. /**
  23754. * An event triggered after rendering the scene
  23755. */
  23756. _this.onAfterRenderObservable = new BABYLON.Observable();
  23757. _this._onAfterRenderObserver = null;
  23758. /**
  23759. * An event triggered before animating the scene
  23760. */
  23761. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23762. /**
  23763. * An event triggered after animations processing
  23764. */
  23765. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23766. /**
  23767. * An event triggered before draw calls are ready to be sent
  23768. */
  23769. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23770. /**
  23771. * An event triggered after draw calls have been sent
  23772. */
  23773. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23774. /**
  23775. * An event triggered when physic simulation is about to be run
  23776. */
  23777. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23778. /**
  23779. * An event triggered when physic simulation has been done
  23780. */
  23781. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23782. /**
  23783. * An event triggered when the scene is ready
  23784. */
  23785. _this.onReadyObservable = new BABYLON.Observable();
  23786. /**
  23787. * An event triggered before rendering a camera
  23788. */
  23789. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23790. _this._onBeforeCameraRenderObserver = null;
  23791. /**
  23792. * An event triggered after rendering a camera
  23793. */
  23794. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23795. _this._onAfterCameraRenderObserver = null;
  23796. /**
  23797. * An event triggered when active meshes evaluation is about to start
  23798. */
  23799. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23800. /**
  23801. * An event triggered when active meshes evaluation is done
  23802. */
  23803. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23804. /**
  23805. * An event triggered when particles rendering is about to start
  23806. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23807. */
  23808. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23809. /**
  23810. * An event triggered when particles rendering is done
  23811. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23812. */
  23813. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23814. /**
  23815. * An event triggered when sprites rendering is about to start
  23816. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23817. */
  23818. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23819. /**
  23820. * An event triggered when sprites rendering is done
  23821. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23822. */
  23823. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23824. /**
  23825. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23826. */
  23827. _this.onDataLoadedObservable = new BABYLON.Observable();
  23828. /**
  23829. * An event triggered when a camera is created
  23830. */
  23831. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23832. /**
  23833. * An event triggered when a camera is removed
  23834. */
  23835. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23836. /**
  23837. * An event triggered when a light is created
  23838. */
  23839. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23840. /**
  23841. * An event triggered when a light is removed
  23842. */
  23843. _this.onLightRemovedObservable = new BABYLON.Observable();
  23844. /**
  23845. * An event triggered when a geometry is created
  23846. */
  23847. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23848. /**
  23849. * An event triggered when a geometry is removed
  23850. */
  23851. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23852. /**
  23853. * An event triggered when a transform node is created
  23854. */
  23855. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23856. /**
  23857. * An event triggered when a transform node is removed
  23858. */
  23859. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23860. /**
  23861. * An event triggered when a mesh is created
  23862. */
  23863. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23864. /**
  23865. * An event triggered when a mesh is removed
  23866. */
  23867. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23868. /**
  23869. * An event triggered when render targets are about to be rendered
  23870. * Can happen multiple times per frame.
  23871. */
  23872. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23873. /**
  23874. * An event triggered when render targets were rendered.
  23875. * Can happen multiple times per frame.
  23876. */
  23877. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23878. /**
  23879. * An event triggered before calculating deterministic simulation step
  23880. */
  23881. _this.onBeforeStepObservable = new BABYLON.Observable();
  23882. /**
  23883. * An event triggered after calculating deterministic simulation step
  23884. */
  23885. _this.onAfterStepObservable = new BABYLON.Observable();
  23886. /**
  23887. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  23888. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23889. * 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)
  23890. */
  23891. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  23892. /**
  23893. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  23894. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23895. * 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)
  23896. */
  23897. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  23898. // Animations
  23899. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23900. /**
  23901. * 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).
  23902. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23903. */
  23904. _this.onPrePointerObservable = new BABYLON.Observable();
  23905. /**
  23906. * Observable event triggered each time an input event is received from the rendering canvas
  23907. */
  23908. _this.onPointerObservable = new BABYLON.Observable();
  23909. _this._meshPickProceed = false;
  23910. _this._currentPickResult = null;
  23911. _this._previousPickResult = null;
  23912. _this._totalPointersPressed = 0;
  23913. _this._doubleClickOccured = false;
  23914. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23915. _this.cameraToUseForPointers = null;
  23916. _this._pointerX = 0;
  23917. _this._pointerY = 0;
  23918. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23919. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23920. _this._startingPointerTime = 0;
  23921. _this._previousStartingPointerTime = 0;
  23922. _this._pointerCaptures = {};
  23923. // Deterministic lockstep
  23924. _this._timeAccumulator = 0;
  23925. _this._currentStepId = 0;
  23926. _this._currentInternalStep = 0;
  23927. // Keyboard
  23928. /**
  23929. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23930. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23931. */
  23932. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23933. /**
  23934. * Observable event triggered each time an keyboard event is received from the hosting window
  23935. */
  23936. _this.onKeyboardObservable = new BABYLON.Observable();
  23937. // Coordinates system
  23938. _this._useRightHandedSystem = false;
  23939. // Fog
  23940. _this._fogEnabled = true;
  23941. _this._fogMode = Scene.FOGMODE_NONE;
  23942. /**
  23943. * Gets or sets the fog color to use
  23944. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23945. */
  23946. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23947. /**
  23948. * Gets or sets the fog density to use
  23949. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23950. */
  23951. _this.fogDensity = 0.1;
  23952. /**
  23953. * Gets or sets the fog start distance to use
  23954. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23955. */
  23956. _this.fogStart = 0;
  23957. /**
  23958. * Gets or sets the fog end distance to use
  23959. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23960. */
  23961. _this.fogEnd = 1000.0;
  23962. // Lights
  23963. _this._shadowsEnabled = true;
  23964. _this._lightsEnabled = true;
  23965. /** All of the active cameras added to this scene. */
  23966. _this.activeCameras = new Array();
  23967. // Textures
  23968. _this._texturesEnabled = true;
  23969. // Particles
  23970. /**
  23971. * Gets or sets a boolean indicating if particles are enabled on this scene
  23972. */
  23973. _this.particlesEnabled = true;
  23974. // Sprites
  23975. /**
  23976. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23977. */
  23978. _this.spritesEnabled = true;
  23979. /**
  23980. * All of the sprite managers added to this scene
  23981. * @see http://doc.babylonjs.com/babylon101/sprites
  23982. */
  23983. _this.spriteManagers = new Array();
  23984. // Skeletons
  23985. _this._skeletonsEnabled = true;
  23986. // Lens flares
  23987. /**
  23988. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23989. */
  23990. _this.lensFlaresEnabled = true;
  23991. // Collisions
  23992. /**
  23993. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23994. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23995. */
  23996. _this.collisionsEnabled = true;
  23997. /**
  23998. * Defines the gravity applied to this scene (used only for collisions)
  23999. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24000. */
  24001. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24002. // Postprocesses
  24003. /**
  24004. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24005. */
  24006. _this.postProcessesEnabled = true;
  24007. /**
  24008. * The list of postprocesses added to the scene
  24009. */
  24010. _this.postProcesses = new Array();
  24011. // Customs render targets
  24012. /**
  24013. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24014. */
  24015. _this.renderTargetsEnabled = true;
  24016. /**
  24017. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24018. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24019. */
  24020. _this.dumpNextRenderTargets = false;
  24021. /**
  24022. * The list of user defined render targets added to the scene
  24023. */
  24024. _this.customRenderTargets = new Array();
  24025. /**
  24026. * Gets the list of meshes imported to the scene through SceneLoader
  24027. */
  24028. _this.importedMeshesFiles = new Array();
  24029. // Probes
  24030. /**
  24031. * Gets or sets a boolean indicating if probes are enabled on this scene
  24032. */
  24033. _this.probesEnabled = true;
  24034. /**
  24035. * The list of reflection probes added to the scene
  24036. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24037. */
  24038. _this.reflectionProbes = new Array();
  24039. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24040. // Procedural textures
  24041. /**
  24042. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24043. */
  24044. _this.proceduralTexturesEnabled = true;
  24045. /**
  24046. * The list of procedural textures added to the scene
  24047. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24048. */
  24049. _this.proceduralTextures = new Array();
  24050. /**
  24051. * The list of sound tracks added to the scene
  24052. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24053. */
  24054. _this.soundTracks = new Array();
  24055. _this._audioEnabled = true;
  24056. _this._headphone = false;
  24057. // Performance counters
  24058. _this._totalVertices = new BABYLON.PerfCounter();
  24059. /** @hidden */
  24060. _this._activeIndices = new BABYLON.PerfCounter();
  24061. /** @hidden */
  24062. _this._activeParticles = new BABYLON.PerfCounter();
  24063. /** @hidden */
  24064. _this._activeBones = new BABYLON.PerfCounter();
  24065. _this._animationTime = 0;
  24066. /**
  24067. * Gets or sets a general scale for animation speed
  24068. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24069. */
  24070. _this.animationTimeScale = 1;
  24071. _this._renderId = 0;
  24072. _this._executeWhenReadyTimeoutId = -1;
  24073. _this._intermediateRendering = false;
  24074. _this._viewUpdateFlag = -1;
  24075. _this._projectionUpdateFlag = -1;
  24076. _this._alternateViewUpdateFlag = -1;
  24077. _this._alternateProjectionUpdateFlag = -1;
  24078. /** @hidden */
  24079. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24080. _this._activeRequests = new Array();
  24081. _this._pendingData = new Array();
  24082. _this._isDisposed = false;
  24083. /**
  24084. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24085. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24086. */
  24087. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24088. _this._activeMeshes = new BABYLON.SmartArray(256);
  24089. _this._processedMaterials = new BABYLON.SmartArray(256);
  24090. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24091. /** @hidden */
  24092. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24093. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24094. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24095. /** @hidden */
  24096. _this._activeAnimatables = new Array();
  24097. _this._transformMatrix = BABYLON.Matrix.Zero();
  24098. _this._useAlternateCameraConfiguration = false;
  24099. _this._alternateRendering = false;
  24100. /**
  24101. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24102. * This is useful if there are more lights that the maximum simulteanous authorized
  24103. */
  24104. _this.requireLightSorting = false;
  24105. _this._depthRenderer = {};
  24106. /**
  24107. * @hidden
  24108. * Backing store of defined scene components.
  24109. */
  24110. _this._components = [];
  24111. /**
  24112. * @hidden
  24113. * Backing store of defined scene components.
  24114. */
  24115. _this._serializableComponents = [];
  24116. /**
  24117. * List of components to register on the next registration step.
  24118. */
  24119. _this._transientComponents = [];
  24120. /**
  24121. * @hidden
  24122. * Defines the actions happening before camera updates.
  24123. */
  24124. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24125. /**
  24126. * @hidden
  24127. * Defines the actions happening during the per mesh ready checks.
  24128. */
  24129. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24130. /**
  24131. * @hidden
  24132. * Defines the actions happening before evaluate active mesh checks.
  24133. */
  24134. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24135. /**
  24136. * @hidden
  24137. * Defines the actions happening during the evaluate sub mesh checks.
  24138. */
  24139. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24140. /**
  24141. * @hidden
  24142. * Defines the actions happening during the active mesh stage.
  24143. */
  24144. _this._activeMeshStage = BABYLON.Stage.Create();
  24145. /**
  24146. * @hidden
  24147. * Defines the actions happening during the per camera render target step.
  24148. */
  24149. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24150. /**
  24151. * @hidden
  24152. * Defines the actions happening just before the active camera is drawing.
  24153. */
  24154. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24155. /**
  24156. * Defines the actions happening just before a rendering group is drawing.
  24157. */
  24158. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24159. /**
  24160. * @hidden
  24161. * Defines the actions happening just after a rendering group has been drawn.
  24162. */
  24163. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24164. /**
  24165. * @hidden
  24166. * Defines the actions happening just after the active camera has been drawn.
  24167. */
  24168. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24169. _this._activeMeshesFrozen = false;
  24170. /** @hidden */
  24171. _this._allowPostProcessClear = true;
  24172. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24173. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24174. _this._engine.scenes.push(_this);
  24175. _this._uid = null;
  24176. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24177. if (BABYLON.PostProcessManager) {
  24178. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24179. }
  24180. if (BABYLON.OutlineRenderer) {
  24181. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24182. }
  24183. if (BABYLON.Tools.IsWindowObjectExist()) {
  24184. _this.attachControl();
  24185. }
  24186. //simplification queue
  24187. if (BABYLON.SimplificationQueue) {
  24188. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24189. }
  24190. //collision coordinator initialization. For now legacy per default.
  24191. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24192. // Uniform Buffer
  24193. _this._createUbo();
  24194. // Default Image processing definition
  24195. if (BABYLON.ImageProcessingConfiguration) {
  24196. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24197. }
  24198. return _this;
  24199. }
  24200. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24201. /** The fog is deactivated */
  24202. get: function () {
  24203. return Scene._FOGMODE_NONE;
  24204. },
  24205. enumerable: true,
  24206. configurable: true
  24207. });
  24208. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24209. /** The fog density is following an exponential function */
  24210. get: function () {
  24211. return Scene._FOGMODE_EXP;
  24212. },
  24213. enumerable: true,
  24214. configurable: true
  24215. });
  24216. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24217. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24218. get: function () {
  24219. return Scene._FOGMODE_EXP2;
  24220. },
  24221. enumerable: true,
  24222. configurable: true
  24223. });
  24224. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24225. /** The fog density is following a linear function. */
  24226. get: function () {
  24227. return Scene._FOGMODE_LINEAR;
  24228. },
  24229. enumerable: true,
  24230. configurable: true
  24231. });
  24232. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24233. /**
  24234. * Texture used in all pbr material as the reflection texture.
  24235. * As in the majority of the scene they are the same (exception for multi room and so on),
  24236. * this is easier to reference from here than from all the materials.
  24237. */
  24238. get: function () {
  24239. return this._environmentTexture;
  24240. },
  24241. /**
  24242. * Texture used in all pbr material as the reflection texture.
  24243. * As in the majority of the scene they are the same (exception for multi room and so on),
  24244. * this is easier to set here than in all the materials.
  24245. */
  24246. set: function (value) {
  24247. if (this._environmentTexture === value) {
  24248. return;
  24249. }
  24250. this._environmentTexture = value;
  24251. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24252. },
  24253. enumerable: true,
  24254. configurable: true
  24255. });
  24256. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24257. /**
  24258. * Default image processing configuration used either in the rendering
  24259. * Forward main pass or through the imageProcessingPostProcess if present.
  24260. * As in the majority of the scene they are the same (exception for multi camera),
  24261. * this is easier to reference from here than from all the materials and post process.
  24262. *
  24263. * No setter as we it is a shared configuration, you can set the values instead.
  24264. */
  24265. get: function () {
  24266. return this._imageProcessingConfiguration;
  24267. },
  24268. enumerable: true,
  24269. configurable: true
  24270. });
  24271. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24272. get: function () {
  24273. return this._forceWireframe;
  24274. },
  24275. /**
  24276. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24277. */
  24278. set: function (value) {
  24279. if (this._forceWireframe === value) {
  24280. return;
  24281. }
  24282. this._forceWireframe = value;
  24283. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24284. },
  24285. enumerable: true,
  24286. configurable: true
  24287. });
  24288. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24289. get: function () {
  24290. return this._forcePointsCloud;
  24291. },
  24292. /**
  24293. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24294. */
  24295. set: function (value) {
  24296. if (this._forcePointsCloud === value) {
  24297. return;
  24298. }
  24299. this._forcePointsCloud = value;
  24300. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24301. },
  24302. enumerable: true,
  24303. configurable: true
  24304. });
  24305. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24306. /**
  24307. * Gets or sets the animation properties override
  24308. */
  24309. get: function () {
  24310. return this._animationPropertiesOverride;
  24311. },
  24312. set: function (value) {
  24313. this._animationPropertiesOverride = value;
  24314. },
  24315. enumerable: true,
  24316. configurable: true
  24317. });
  24318. Object.defineProperty(Scene.prototype, "onDispose", {
  24319. /** Sets a function to be executed when this scene is disposed. */
  24320. set: function (callback) {
  24321. if (this._onDisposeObserver) {
  24322. this.onDisposeObservable.remove(this._onDisposeObserver);
  24323. }
  24324. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24325. },
  24326. enumerable: true,
  24327. configurable: true
  24328. });
  24329. Object.defineProperty(Scene.prototype, "beforeRender", {
  24330. /** Sets a function to be executed before rendering this scene */
  24331. set: function (callback) {
  24332. if (this._onBeforeRenderObserver) {
  24333. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24334. }
  24335. if (callback) {
  24336. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24337. }
  24338. },
  24339. enumerable: true,
  24340. configurable: true
  24341. });
  24342. Object.defineProperty(Scene.prototype, "afterRender", {
  24343. /** Sets a function to be executed after rendering this scene */
  24344. set: function (callback) {
  24345. if (this._onAfterRenderObserver) {
  24346. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24347. }
  24348. if (callback) {
  24349. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24350. }
  24351. },
  24352. enumerable: true,
  24353. configurable: true
  24354. });
  24355. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24356. /** Sets a function to be executed before rendering a camera*/
  24357. set: function (callback) {
  24358. if (this._onBeforeCameraRenderObserver) {
  24359. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24360. }
  24361. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24362. },
  24363. enumerable: true,
  24364. configurable: true
  24365. });
  24366. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24367. /** Sets a function to be executed after rendering a camera*/
  24368. set: function (callback) {
  24369. if (this._onAfterCameraRenderObserver) {
  24370. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24371. }
  24372. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24373. },
  24374. enumerable: true,
  24375. configurable: true
  24376. });
  24377. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24378. /**
  24379. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24380. */
  24381. get: function () {
  24382. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24388. get: function () {
  24389. return this._useRightHandedSystem;
  24390. },
  24391. /**
  24392. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24393. */
  24394. set: function (value) {
  24395. if (this._useRightHandedSystem === value) {
  24396. return;
  24397. }
  24398. this._useRightHandedSystem = value;
  24399. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. /**
  24405. * Sets the step Id used by deterministic lock step
  24406. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24407. * @param newStepId defines the step Id
  24408. */
  24409. Scene.prototype.setStepId = function (newStepId) {
  24410. this._currentStepId = newStepId;
  24411. };
  24412. ;
  24413. /**
  24414. * Gets the step Id used by deterministic lock step
  24415. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24416. * @returns the step Id
  24417. */
  24418. Scene.prototype.getStepId = function () {
  24419. return this._currentStepId;
  24420. };
  24421. ;
  24422. /**
  24423. * Gets the internal step used by deterministic lock step
  24424. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24425. * @returns the internal step
  24426. */
  24427. Scene.prototype.getInternalStep = function () {
  24428. return this._currentInternalStep;
  24429. };
  24430. ;
  24431. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24432. get: function () {
  24433. return this._fogEnabled;
  24434. },
  24435. /**
  24436. * Gets or sets a boolean indicating if fog is enabled on this scene
  24437. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24438. */
  24439. set: function (value) {
  24440. if (this._fogEnabled === value) {
  24441. return;
  24442. }
  24443. this._fogEnabled = value;
  24444. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Scene.prototype, "fogMode", {
  24450. get: function () {
  24451. return this._fogMode;
  24452. },
  24453. /**
  24454. * Gets or sets the fog mode to use
  24455. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24456. */
  24457. set: function (value) {
  24458. if (this._fogMode === value) {
  24459. return;
  24460. }
  24461. this._fogMode = value;
  24462. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24463. },
  24464. enumerable: true,
  24465. configurable: true
  24466. });
  24467. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24468. get: function () {
  24469. return this._shadowsEnabled;
  24470. },
  24471. /**
  24472. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24473. */
  24474. set: function (value) {
  24475. if (this._shadowsEnabled === value) {
  24476. return;
  24477. }
  24478. this._shadowsEnabled = value;
  24479. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24480. },
  24481. enumerable: true,
  24482. configurable: true
  24483. });
  24484. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24485. get: function () {
  24486. return this._lightsEnabled;
  24487. },
  24488. /**
  24489. * Gets or sets a boolean indicating if lights are enabled on this scene
  24490. */
  24491. set: function (value) {
  24492. if (this._lightsEnabled === value) {
  24493. return;
  24494. }
  24495. this._lightsEnabled = value;
  24496. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24497. },
  24498. enumerable: true,
  24499. configurable: true
  24500. });
  24501. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24502. /** The default material used on meshes when no material is affected */
  24503. get: function () {
  24504. if (!this._defaultMaterial) {
  24505. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24506. }
  24507. return this._defaultMaterial;
  24508. },
  24509. /** The default material used on meshes when no material is affected */
  24510. set: function (value) {
  24511. this._defaultMaterial = value;
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24517. get: function () {
  24518. return this._texturesEnabled;
  24519. },
  24520. /**
  24521. * Gets or sets a boolean indicating if textures are enabled on this scene
  24522. */
  24523. set: function (value) {
  24524. if (this._texturesEnabled === value) {
  24525. return;
  24526. }
  24527. this._texturesEnabled = value;
  24528. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24529. },
  24530. enumerable: true,
  24531. configurable: true
  24532. });
  24533. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24534. get: function () {
  24535. return this._skeletonsEnabled;
  24536. },
  24537. /**
  24538. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24539. */
  24540. set: function (value) {
  24541. if (this._skeletonsEnabled === value) {
  24542. return;
  24543. }
  24544. this._skeletonsEnabled = value;
  24545. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24546. },
  24547. enumerable: true,
  24548. configurable: true
  24549. });
  24550. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24551. /**
  24552. * Gets the postprocess render pipeline manager
  24553. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24554. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24555. */
  24556. get: function () {
  24557. if (!this._postProcessRenderPipelineManager) {
  24558. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24559. }
  24560. return this._postProcessRenderPipelineManager;
  24561. },
  24562. enumerable: true,
  24563. configurable: true
  24564. });
  24565. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24566. /**
  24567. * Gets the main soundtrack associated with the scene
  24568. */
  24569. get: function () {
  24570. if (!this._mainSoundTrack) {
  24571. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24572. }
  24573. return this._mainSoundTrack;
  24574. },
  24575. enumerable: true,
  24576. configurable: true
  24577. });
  24578. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24579. /** @hidden */
  24580. get: function () {
  24581. return this._alternateRendering;
  24582. },
  24583. enumerable: true,
  24584. configurable: true
  24585. });
  24586. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24587. /**
  24588. * Gets the list of frustum planes (built from the active camera)
  24589. */
  24590. get: function () {
  24591. return this._frustumPlanes;
  24592. },
  24593. enumerable: true,
  24594. configurable: true
  24595. });
  24596. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24597. /**
  24598. * Gets the current geometry buffer associated to the scene.
  24599. */
  24600. get: function () {
  24601. return this._geometryBufferRenderer;
  24602. },
  24603. /**
  24604. * Sets the current geometry buffer for the scene.
  24605. */
  24606. set: function (geometryBufferRenderer) {
  24607. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24608. this._geometryBufferRenderer = geometryBufferRenderer;
  24609. }
  24610. },
  24611. enumerable: true,
  24612. configurable: true
  24613. });
  24614. /**
  24615. * Registers the transient components if needed.
  24616. */
  24617. Scene.prototype._registerTransientComponents = function () {
  24618. // Register components that have been associated lately to the scene.
  24619. if (this._transientComponents.length > 0) {
  24620. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24621. var component = _a[_i];
  24622. component.register();
  24623. }
  24624. this._transientComponents = [];
  24625. }
  24626. };
  24627. /**
  24628. * @hidden
  24629. * Add a component to the scene.
  24630. * Note that the ccomponent could be registered on th next frame if this is called after
  24631. * the register component stage.
  24632. * @param component Defines the component to add to the scene
  24633. */
  24634. Scene.prototype._addComponent = function (component) {
  24635. this._components.push(component);
  24636. this._transientComponents.push(component);
  24637. var serializableComponent = component;
  24638. if (serializableComponent.addFromContainer) {
  24639. this._serializableComponents.push(serializableComponent);
  24640. }
  24641. };
  24642. /**
  24643. * @hidden
  24644. * Gets a component from the scene.
  24645. * @param name defines the name of the component to retrieve
  24646. * @returns the component or null if not present
  24647. */
  24648. Scene.prototype._getComponent = function (name) {
  24649. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24650. var component = _a[_i];
  24651. if (component.name === name) {
  24652. return component;
  24653. }
  24654. }
  24655. return null;
  24656. };
  24657. Object.defineProperty(Scene.prototype, "debugLayer", {
  24658. /**
  24659. * Gets the debug layer (aka Inspector) associated with the scene
  24660. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24661. */
  24662. get: function () {
  24663. if (!this._debugLayer) {
  24664. this._debugLayer = new BABYLON.DebugLayer(this);
  24665. }
  24666. return this._debugLayer;
  24667. },
  24668. enumerable: true,
  24669. configurable: true
  24670. });
  24671. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24672. /**
  24673. * Gets a boolean indicating if collisions are processed on a web worker
  24674. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24675. */
  24676. get: function () {
  24677. return this._workerCollisions;
  24678. },
  24679. set: function (enabled) {
  24680. if (!BABYLON.CollisionCoordinatorLegacy) {
  24681. return;
  24682. }
  24683. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24684. this._workerCollisions = enabled;
  24685. if (this.collisionCoordinator) {
  24686. this.collisionCoordinator.destroy();
  24687. }
  24688. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24689. this.collisionCoordinator.init(this);
  24690. },
  24691. enumerable: true,
  24692. configurable: true
  24693. });
  24694. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24695. /**
  24696. * Gets the octree used to boost mesh selection (picking)
  24697. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24698. */
  24699. get: function () {
  24700. return this._selectionOctree;
  24701. },
  24702. enumerable: true,
  24703. configurable: true
  24704. });
  24705. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24706. /**
  24707. * Gets the mesh that is currently under the pointer
  24708. */
  24709. get: function () {
  24710. return this._pointerOverMesh;
  24711. },
  24712. enumerable: true,
  24713. configurable: true
  24714. });
  24715. Object.defineProperty(Scene.prototype, "pointerX", {
  24716. /**
  24717. * Gets the current on-screen X position of the pointer
  24718. */
  24719. get: function () {
  24720. return this._pointerX;
  24721. },
  24722. enumerable: true,
  24723. configurable: true
  24724. });
  24725. Object.defineProperty(Scene.prototype, "pointerY", {
  24726. /**
  24727. * Gets the current on-screen Y position of the pointer
  24728. */
  24729. get: function () {
  24730. return this._pointerY;
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. /**
  24736. * Gets the cached material (ie. the latest rendered one)
  24737. * @returns the cached material
  24738. */
  24739. Scene.prototype.getCachedMaterial = function () {
  24740. return this._cachedMaterial;
  24741. };
  24742. /**
  24743. * Gets the cached effect (ie. the latest rendered one)
  24744. * @returns the cached effect
  24745. */
  24746. Scene.prototype.getCachedEffect = function () {
  24747. return this._cachedEffect;
  24748. };
  24749. /**
  24750. * Gets the cached visibility state (ie. the latest rendered one)
  24751. * @returns the cached visibility state
  24752. */
  24753. Scene.prototype.getCachedVisibility = function () {
  24754. return this._cachedVisibility;
  24755. };
  24756. /**
  24757. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24758. * @param material defines the current material
  24759. * @param effect defines the current effect
  24760. * @param visibility defines the current visibility state
  24761. * @returns true if one parameter is not cached
  24762. */
  24763. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24764. if (visibility === void 0) { visibility = 1; }
  24765. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24766. };
  24767. /**
  24768. * Gets the outline renderer associated with the scene
  24769. * @returns a OutlineRenderer
  24770. */
  24771. Scene.prototype.getOutlineRenderer = function () {
  24772. return this._outlineRenderer;
  24773. };
  24774. /**
  24775. * Gets the engine associated with the scene
  24776. * @returns an Engine
  24777. */
  24778. Scene.prototype.getEngine = function () {
  24779. return this._engine;
  24780. };
  24781. /**
  24782. * Gets the total number of vertices rendered per frame
  24783. * @returns the total number of vertices rendered per frame
  24784. */
  24785. Scene.prototype.getTotalVertices = function () {
  24786. return this._totalVertices.current;
  24787. };
  24788. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24789. /**
  24790. * Gets the performance counter for total vertices
  24791. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24792. */
  24793. get: function () {
  24794. return this._totalVertices;
  24795. },
  24796. enumerable: true,
  24797. configurable: true
  24798. });
  24799. /**
  24800. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24801. * @returns the total number of active indices rendered per frame
  24802. */
  24803. Scene.prototype.getActiveIndices = function () {
  24804. return this._activeIndices.current;
  24805. };
  24806. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24807. /**
  24808. * Gets the performance counter for active indices
  24809. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24810. */
  24811. get: function () {
  24812. return this._activeIndices;
  24813. },
  24814. enumerable: true,
  24815. configurable: true
  24816. });
  24817. /**
  24818. * Gets the total number of active particles rendered per frame
  24819. * @returns the total number of active particles rendered per frame
  24820. */
  24821. Scene.prototype.getActiveParticles = function () {
  24822. return this._activeParticles.current;
  24823. };
  24824. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24825. /**
  24826. * Gets the performance counter for active particles
  24827. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24828. */
  24829. get: function () {
  24830. return this._activeParticles;
  24831. },
  24832. enumerable: true,
  24833. configurable: true
  24834. });
  24835. /**
  24836. * Gets the total number of active bones rendered per frame
  24837. * @returns the total number of active bones rendered per frame
  24838. */
  24839. Scene.prototype.getActiveBones = function () {
  24840. return this._activeBones.current;
  24841. };
  24842. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24843. /**
  24844. * Gets the performance counter for active bones
  24845. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24846. */
  24847. get: function () {
  24848. return this._activeBones;
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. /** @hidden */
  24854. Scene.prototype.getInterFramePerfCounter = function () {
  24855. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24856. return 0;
  24857. };
  24858. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24859. /** @hidden */
  24860. get: function () {
  24861. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24862. return null;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. /** @hidden */
  24868. Scene.prototype.getLastFrameDuration = function () {
  24869. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24870. return 0;
  24871. };
  24872. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24873. /** @hidden */
  24874. get: function () {
  24875. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24876. return null;
  24877. },
  24878. enumerable: true,
  24879. configurable: true
  24880. });
  24881. /** @hidden */
  24882. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24883. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24884. return 0;
  24885. };
  24886. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24887. /** @hidden */
  24888. get: function () {
  24889. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24890. return null;
  24891. },
  24892. enumerable: true,
  24893. configurable: true
  24894. });
  24895. /**
  24896. * Gets the array of active meshes
  24897. * @returns an array of AbstractMesh
  24898. */
  24899. Scene.prototype.getActiveMeshes = function () {
  24900. return this._activeMeshes;
  24901. };
  24902. /** @hidden */
  24903. Scene.prototype.getRenderTargetsDuration = function () {
  24904. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24905. return 0;
  24906. };
  24907. /** @hidden */
  24908. Scene.prototype.getRenderDuration = function () {
  24909. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24910. return 0;
  24911. };
  24912. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24913. /** @hidden */
  24914. get: function () {
  24915. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24916. return null;
  24917. },
  24918. enumerable: true,
  24919. configurable: true
  24920. });
  24921. /** @hidden */
  24922. Scene.prototype.getParticlesDuration = function () {
  24923. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24924. return 0;
  24925. };
  24926. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24927. /** @hidden */
  24928. get: function () {
  24929. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24930. return null;
  24931. },
  24932. enumerable: true,
  24933. configurable: true
  24934. });
  24935. /** @hidden */
  24936. Scene.prototype.getSpritesDuration = function () {
  24937. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24938. return 0;
  24939. };
  24940. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24941. /** @hidden */
  24942. get: function () {
  24943. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24944. return null;
  24945. },
  24946. enumerable: true,
  24947. configurable: true
  24948. });
  24949. /**
  24950. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24951. * @returns a number
  24952. */
  24953. Scene.prototype.getAnimationRatio = function () {
  24954. return this._animationRatio !== undefined ? this._animationRatio : 1;
  24955. };
  24956. /**
  24957. * Gets an unique Id for the current frame
  24958. * @returns a number
  24959. */
  24960. Scene.prototype.getRenderId = function () {
  24961. return this._renderId;
  24962. };
  24963. /** Call this function if you want to manually increment the render Id*/
  24964. Scene.prototype.incrementRenderId = function () {
  24965. this._renderId++;
  24966. };
  24967. Scene.prototype._updatePointerPosition = function (evt) {
  24968. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24969. if (!canvasRect) {
  24970. return;
  24971. }
  24972. this._pointerX = evt.clientX - canvasRect.left;
  24973. this._pointerY = evt.clientY - canvasRect.top;
  24974. this._unTranslatedPointerX = this._pointerX;
  24975. this._unTranslatedPointerY = this._pointerY;
  24976. };
  24977. Scene.prototype._createUbo = function () {
  24978. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24979. this._sceneUbo.addUniform("viewProjection", 16);
  24980. this._sceneUbo.addUniform("view", 16);
  24981. };
  24982. Scene.prototype._createAlternateUbo = function () {
  24983. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24984. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24985. this._alternateSceneUbo.addUniform("view", 16);
  24986. };
  24987. // Pointers handling
  24988. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24989. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24990. if (result) {
  24991. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24992. }
  24993. return result;
  24994. };
  24995. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24996. if (pointerInfo.pickInfo) {
  24997. if (!pointerInfo.pickInfo.ray) {
  24998. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24999. }
  25000. }
  25001. };
  25002. /**
  25003. * Use this method to simulate a pointer move on a mesh
  25004. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25005. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25006. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25007. * @returns the current scene
  25008. */
  25009. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25010. var evt = new PointerEvent("pointermove", pointerEventInit);
  25011. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25012. return this;
  25013. }
  25014. return this._processPointerMove(pickResult, evt);
  25015. };
  25016. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25017. var canvas = this._engine.getRenderingCanvas();
  25018. if (!canvas) {
  25019. return this;
  25020. }
  25021. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25022. this.setPointerOverSprite(null);
  25023. this.setPointerOverMesh(pickResult.pickedMesh);
  25024. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25025. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25026. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25027. }
  25028. else {
  25029. canvas.style.cursor = this.hoverCursor;
  25030. }
  25031. }
  25032. else {
  25033. canvas.style.cursor = this.defaultCursor;
  25034. }
  25035. }
  25036. else {
  25037. this.setPointerOverMesh(null);
  25038. // Sprites
  25039. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25040. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25041. this.setPointerOverSprite(pickResult.pickedSprite);
  25042. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25043. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25044. }
  25045. else {
  25046. canvas.style.cursor = this.hoverCursor;
  25047. }
  25048. }
  25049. else {
  25050. this.setPointerOverSprite(null);
  25051. // Restore pointer
  25052. canvas.style.cursor = this.defaultCursor;
  25053. }
  25054. }
  25055. if (pickResult) {
  25056. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25057. if (this.onPointerMove) {
  25058. this.onPointerMove(evt, pickResult, type);
  25059. }
  25060. if (this.onPointerObservable.hasObservers()) {
  25061. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25062. this._setRayOnPointerInfo(pi);
  25063. this.onPointerObservable.notifyObservers(pi, type);
  25064. }
  25065. }
  25066. return this;
  25067. };
  25068. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25069. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25070. if (pickResult) {
  25071. pi.ray = pickResult.ray;
  25072. }
  25073. this.onPrePointerObservable.notifyObservers(pi, type);
  25074. if (pi.skipOnPointerObservable) {
  25075. return true;
  25076. }
  25077. else {
  25078. return false;
  25079. }
  25080. };
  25081. /**
  25082. * Use this method to simulate a pointer down on a mesh
  25083. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25084. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25085. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25086. * @returns the current scene
  25087. */
  25088. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25089. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25090. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25091. return this;
  25092. }
  25093. return this._processPointerDown(pickResult, evt);
  25094. };
  25095. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25096. var _this = this;
  25097. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25098. this._pickedDownMesh = pickResult.pickedMesh;
  25099. var actionManager = pickResult.pickedMesh.actionManager;
  25100. if (actionManager) {
  25101. if (actionManager.hasPickTriggers) {
  25102. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25103. switch (evt.button) {
  25104. case 0:
  25105. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25106. break;
  25107. case 1:
  25108. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25109. break;
  25110. case 2:
  25111. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25112. break;
  25113. }
  25114. }
  25115. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25116. window.setTimeout(function () {
  25117. 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);
  25118. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25119. if (_this._totalPointersPressed !== 0 &&
  25120. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25121. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25122. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25123. _this._startingPointerTime = 0;
  25124. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25125. }
  25126. }
  25127. }, Scene.LongPressDelay);
  25128. }
  25129. }
  25130. }
  25131. if (pickResult) {
  25132. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25133. if (this.onPointerDown) {
  25134. this.onPointerDown(evt, pickResult, type);
  25135. }
  25136. if (this.onPointerObservable.hasObservers()) {
  25137. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25138. this._setRayOnPointerInfo(pi);
  25139. this.onPointerObservable.notifyObservers(pi, type);
  25140. }
  25141. }
  25142. return this;
  25143. };
  25144. /**
  25145. * Use this method to simulate a pointer up on a mesh
  25146. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25147. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25148. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25149. * @returns the current scene
  25150. */
  25151. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25152. var evt = new PointerEvent("pointerup", pointerEventInit);
  25153. var clickInfo = new ClickInfo();
  25154. clickInfo.singleClick = true;
  25155. clickInfo.ignore = true;
  25156. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25157. return this;
  25158. }
  25159. return this._processPointerUp(pickResult, evt, clickInfo);
  25160. };
  25161. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25162. if (pickResult && pickResult && pickResult.pickedMesh) {
  25163. this._pickedUpMesh = pickResult.pickedMesh;
  25164. if (this._pickedDownMesh === this._pickedUpMesh) {
  25165. if (this.onPointerPick) {
  25166. this.onPointerPick(evt, pickResult);
  25167. }
  25168. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25169. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25170. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25171. this._setRayOnPointerInfo(pi);
  25172. this.onPointerObservable.notifyObservers(pi, type_1);
  25173. }
  25174. }
  25175. if (pickResult.pickedMesh.actionManager) {
  25176. if (clickInfo.ignore) {
  25177. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25178. }
  25179. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25180. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25181. }
  25182. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25183. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25184. }
  25185. }
  25186. }
  25187. if (this._pickedDownMesh &&
  25188. this._pickedDownMesh.actionManager &&
  25189. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25190. this._pickedDownMesh !== this._pickedUpMesh) {
  25191. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25192. }
  25193. var type = BABYLON.PointerEventTypes.POINTERUP;
  25194. if (this.onPointerObservable.hasObservers()) {
  25195. if (!clickInfo.ignore) {
  25196. if (!clickInfo.hasSwiped) {
  25197. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25198. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25199. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25200. this._setRayOnPointerInfo(pi);
  25201. this.onPointerObservable.notifyObservers(pi, type_2);
  25202. }
  25203. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25204. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25205. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25206. this._setRayOnPointerInfo(pi);
  25207. this.onPointerObservable.notifyObservers(pi, type_3);
  25208. }
  25209. }
  25210. }
  25211. else {
  25212. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25213. this._setRayOnPointerInfo(pi);
  25214. this.onPointerObservable.notifyObservers(pi, type);
  25215. }
  25216. }
  25217. if (this.onPointerUp) {
  25218. this.onPointerUp(evt, pickResult, type);
  25219. }
  25220. return this;
  25221. };
  25222. /**
  25223. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25224. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25225. * @returns true if the pointer was captured
  25226. */
  25227. Scene.prototype.isPointerCaptured = function (pointerId) {
  25228. if (pointerId === void 0) { pointerId = 0; }
  25229. return this._pointerCaptures[pointerId];
  25230. };
  25231. /**
  25232. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25233. * @param attachUp defines if you want to attach events to pointerup
  25234. * @param attachDown defines if you want to attach events to pointerdown
  25235. * @param attachMove defines if you want to attach events to pointermove
  25236. */
  25237. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25238. var _this = this;
  25239. if (attachUp === void 0) { attachUp = true; }
  25240. if (attachDown === void 0) { attachDown = true; }
  25241. if (attachMove === void 0) { attachMove = true; }
  25242. this._initActionManager = function (act, clickInfo) {
  25243. if (!_this._meshPickProceed) {
  25244. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25245. _this._currentPickResult = pickResult;
  25246. if (pickResult) {
  25247. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25248. }
  25249. _this._meshPickProceed = true;
  25250. }
  25251. return act;
  25252. };
  25253. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25254. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25255. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25256. btn !== _this._previousButtonPressed) {
  25257. _this._doubleClickOccured = false;
  25258. clickInfo.singleClick = true;
  25259. clickInfo.ignore = false;
  25260. cb(clickInfo, _this._currentPickResult);
  25261. }
  25262. };
  25263. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25264. var clickInfo = new ClickInfo();
  25265. _this._currentPickResult = null;
  25266. var act = null;
  25267. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25268. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25269. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25270. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25271. act = _this._initActionManager(act, clickInfo);
  25272. if (act)
  25273. checkPicking = act.hasPickTriggers;
  25274. }
  25275. if (checkPicking) {
  25276. var btn = evt.button;
  25277. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25278. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25279. if (!clickInfo.hasSwiped) {
  25280. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25281. if (!checkSingleClickImmediately) {
  25282. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25283. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25284. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25285. act = _this._initActionManager(act, clickInfo);
  25286. if (act)
  25287. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25288. }
  25289. }
  25290. if (checkSingleClickImmediately) {
  25291. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25292. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25293. btn !== _this._previousButtonPressed) {
  25294. clickInfo.singleClick = true;
  25295. cb(clickInfo, _this._currentPickResult);
  25296. }
  25297. }
  25298. // at least one double click is required to be check and exclusive double click is enabled
  25299. else {
  25300. // wait that no double click has been raised during the double click delay
  25301. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25302. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25303. }
  25304. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25305. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25306. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25307. act = _this._initActionManager(act, clickInfo);
  25308. if (act)
  25309. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25310. }
  25311. if (checkDoubleClick) {
  25312. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25313. if (btn === _this._previousButtonPressed &&
  25314. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25315. !_this._doubleClickOccured) {
  25316. // pointer has not moved for 2 clicks, it's a double click
  25317. if (!clickInfo.hasSwiped &&
  25318. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25319. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25320. _this._previousStartingPointerTime = 0;
  25321. _this._doubleClickOccured = true;
  25322. clickInfo.doubleClick = true;
  25323. clickInfo.ignore = false;
  25324. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25325. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25326. }
  25327. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25328. cb(clickInfo, _this._currentPickResult);
  25329. }
  25330. // if the two successive clicks are too far, it's just two simple clicks
  25331. else {
  25332. _this._doubleClickOccured = false;
  25333. _this._previousStartingPointerTime = _this._startingPointerTime;
  25334. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25335. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25336. _this._previousButtonPressed = btn;
  25337. if (Scene.ExclusiveDoubleClickMode) {
  25338. if (_this._previousDelayedSimpleClickTimeout) {
  25339. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25340. }
  25341. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25342. cb(clickInfo, _this._previousPickResult);
  25343. }
  25344. else {
  25345. cb(clickInfo, _this._currentPickResult);
  25346. }
  25347. }
  25348. }
  25349. // just the first click of the double has been raised
  25350. else {
  25351. _this._doubleClickOccured = false;
  25352. _this._previousStartingPointerTime = _this._startingPointerTime;
  25353. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25354. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25355. _this._previousButtonPressed = btn;
  25356. }
  25357. }
  25358. }
  25359. }
  25360. clickInfo.ignore = true;
  25361. cb(clickInfo, _this._currentPickResult);
  25362. };
  25363. this._spritePredicate = function (sprite) {
  25364. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25365. };
  25366. this._onPointerMove = function (evt) {
  25367. _this._updatePointerPosition(evt);
  25368. // PreObservable support
  25369. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25370. return;
  25371. }
  25372. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25373. return;
  25374. }
  25375. if (!_this.pointerMovePredicate) {
  25376. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25377. }
  25378. // Meshes
  25379. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25380. _this._processPointerMove(pickResult, evt);
  25381. };
  25382. this._onPointerDown = function (evt) {
  25383. _this._totalPointersPressed++;
  25384. _this._pickedDownMesh = null;
  25385. _this._meshPickProceed = false;
  25386. _this._updatePointerPosition(evt);
  25387. if (_this.preventDefaultOnPointerDown && canvas) {
  25388. evt.preventDefault();
  25389. canvas.focus();
  25390. }
  25391. // PreObservable support
  25392. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25393. return;
  25394. }
  25395. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25396. return;
  25397. }
  25398. _this._pointerCaptures[evt.pointerId] = true;
  25399. _this._startingPointerPosition.x = _this._pointerX;
  25400. _this._startingPointerPosition.y = _this._pointerY;
  25401. _this._startingPointerTime = Date.now();
  25402. if (!_this.pointerDownPredicate) {
  25403. _this.pointerDownPredicate = function (mesh) {
  25404. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25405. };
  25406. }
  25407. // Meshes
  25408. _this._pickedDownMesh = null;
  25409. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25410. _this._processPointerDown(pickResult, evt);
  25411. // Sprites
  25412. _this._pickedDownSprite = null;
  25413. if (_this.spriteManagers.length > 0) {
  25414. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25415. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25416. if (pickResult.pickedSprite.actionManager) {
  25417. _this._pickedDownSprite = pickResult.pickedSprite;
  25418. switch (evt.button) {
  25419. case 0:
  25420. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25421. break;
  25422. case 1:
  25423. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25424. break;
  25425. case 2:
  25426. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25427. break;
  25428. }
  25429. if (pickResult.pickedSprite.actionManager) {
  25430. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25431. }
  25432. }
  25433. }
  25434. }
  25435. };
  25436. this._onPointerUp = function (evt) {
  25437. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25438. return; // So we need to test it the pointer down was pressed before.
  25439. }
  25440. _this._totalPointersPressed--;
  25441. _this._pickedUpMesh = null;
  25442. _this._meshPickProceed = false;
  25443. _this._updatePointerPosition(evt);
  25444. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25445. // PreObservable support
  25446. if (_this.onPrePointerObservable.hasObservers()) {
  25447. if (!clickInfo.ignore) {
  25448. if (!clickInfo.hasSwiped) {
  25449. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25450. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25451. return;
  25452. }
  25453. }
  25454. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25455. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25456. return;
  25457. }
  25458. }
  25459. }
  25460. }
  25461. else {
  25462. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25463. return;
  25464. }
  25465. }
  25466. }
  25467. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25468. return;
  25469. }
  25470. _this._pointerCaptures[evt.pointerId] = false;
  25471. if (!_this.pointerUpPredicate) {
  25472. _this.pointerUpPredicate = function (mesh) {
  25473. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25474. };
  25475. }
  25476. // Meshes
  25477. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25478. _this._initActionManager(null, clickInfo);
  25479. }
  25480. if (!pickResult) {
  25481. pickResult = _this._currentPickResult;
  25482. }
  25483. _this._processPointerUp(pickResult, evt, clickInfo);
  25484. // Sprites
  25485. if (!clickInfo.ignore) {
  25486. if (_this.spriteManagers.length > 0) {
  25487. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25488. if (spritePickResult) {
  25489. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25490. if (spritePickResult.pickedSprite.actionManager) {
  25491. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25492. if (spritePickResult.pickedSprite.actionManager) {
  25493. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25494. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25495. }
  25496. }
  25497. }
  25498. }
  25499. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25500. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25501. }
  25502. }
  25503. }
  25504. }
  25505. _this._previousPickResult = _this._currentPickResult;
  25506. });
  25507. };
  25508. this._onKeyDown = function (evt) {
  25509. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25510. if (_this.onPreKeyboardObservable.hasObservers()) {
  25511. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25512. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25513. if (pi.skipOnPointerObservable) {
  25514. return;
  25515. }
  25516. }
  25517. if (_this.onKeyboardObservable.hasObservers()) {
  25518. var pi = new BABYLON.KeyboardInfo(type, evt);
  25519. _this.onKeyboardObservable.notifyObservers(pi, type);
  25520. }
  25521. if (_this.actionManager) {
  25522. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25523. }
  25524. };
  25525. this._onKeyUp = function (evt) {
  25526. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25527. if (_this.onPreKeyboardObservable.hasObservers()) {
  25528. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25529. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25530. if (pi.skipOnPointerObservable) {
  25531. return;
  25532. }
  25533. }
  25534. if (_this.onKeyboardObservable.hasObservers()) {
  25535. var pi = new BABYLON.KeyboardInfo(type, evt);
  25536. _this.onKeyboardObservable.notifyObservers(pi, type);
  25537. }
  25538. if (_this.actionManager) {
  25539. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25540. }
  25541. };
  25542. var engine = this.getEngine();
  25543. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25544. if (!canvas) {
  25545. return;
  25546. }
  25547. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25548. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25549. });
  25550. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25551. if (!canvas) {
  25552. return;
  25553. }
  25554. canvas.removeEventListener("keydown", _this._onKeyDown);
  25555. canvas.removeEventListener("keyup", _this._onKeyUp);
  25556. });
  25557. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25558. var canvas = this._engine.getRenderingCanvas();
  25559. if (!canvas) {
  25560. return;
  25561. }
  25562. if (attachMove) {
  25563. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25564. // Wheel
  25565. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25566. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25567. }
  25568. if (attachDown) {
  25569. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25570. }
  25571. if (attachUp) {
  25572. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25573. }
  25574. canvas.tabIndex = 1;
  25575. };
  25576. /** Detaches all event handlers*/
  25577. Scene.prototype.detachControl = function () {
  25578. var engine = this.getEngine();
  25579. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25580. var canvas = engine.getRenderingCanvas();
  25581. if (!canvas) {
  25582. return;
  25583. }
  25584. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25585. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25586. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25587. if (this._onCanvasBlurObserver) {
  25588. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25589. }
  25590. if (this._onCanvasFocusObserver) {
  25591. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25592. }
  25593. // Wheel
  25594. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25595. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25596. // Keyboard
  25597. canvas.removeEventListener("keydown", this._onKeyDown);
  25598. canvas.removeEventListener("keyup", this._onKeyUp);
  25599. // Observables
  25600. this.onKeyboardObservable.clear();
  25601. this.onPreKeyboardObservable.clear();
  25602. this.onPointerObservable.clear();
  25603. this.onPrePointerObservable.clear();
  25604. };
  25605. /**
  25606. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25607. * Delay loaded resources are not taking in account
  25608. * @return true if all required resources are ready
  25609. */
  25610. Scene.prototype.isReady = function () {
  25611. if (this._isDisposed) {
  25612. return false;
  25613. }
  25614. if (this._pendingData.length > 0) {
  25615. return false;
  25616. }
  25617. var index;
  25618. var engine = this.getEngine();
  25619. // Geometries
  25620. for (index = 0; index < this.geometries.length; index++) {
  25621. var geometry = this.geometries[index];
  25622. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25623. return false;
  25624. }
  25625. }
  25626. // Meshes
  25627. for (index = 0; index < this.meshes.length; index++) {
  25628. var mesh = this.meshes[index];
  25629. if (!mesh.isEnabled()) {
  25630. continue;
  25631. }
  25632. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25633. continue;
  25634. }
  25635. if (!mesh.isReady(true)) {
  25636. return false;
  25637. }
  25638. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25639. // Is Ready For Mesh
  25640. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25641. var step = _a[_i];
  25642. if (!step.action(mesh, hardwareInstancedRendering)) {
  25643. return false;
  25644. }
  25645. }
  25646. }
  25647. // Post-processes
  25648. if (this.activeCameras && this.activeCameras.length > 0) {
  25649. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25650. var camera = _c[_b];
  25651. if (!camera.isReady(true)) {
  25652. return false;
  25653. }
  25654. }
  25655. }
  25656. else if (this.activeCamera) {
  25657. if (!this.activeCamera.isReady(true)) {
  25658. return false;
  25659. }
  25660. }
  25661. // Particles
  25662. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25663. var particleSystem = _e[_d];
  25664. if (!particleSystem.isReady()) {
  25665. return false;
  25666. }
  25667. }
  25668. return true;
  25669. };
  25670. /** Resets all cached information relative to material (including effect and visibility) */
  25671. Scene.prototype.resetCachedMaterial = function () {
  25672. this._cachedMaterial = null;
  25673. this._cachedEffect = null;
  25674. this._cachedVisibility = null;
  25675. };
  25676. /**
  25677. * Registers a function to be called before every frame render
  25678. * @param func defines the function to register
  25679. */
  25680. Scene.prototype.registerBeforeRender = function (func) {
  25681. this.onBeforeRenderObservable.add(func);
  25682. };
  25683. /**
  25684. * Unregisters a function called before every frame render
  25685. * @param func defines the function to unregister
  25686. */
  25687. Scene.prototype.unregisterBeforeRender = function (func) {
  25688. this.onBeforeRenderObservable.removeCallback(func);
  25689. };
  25690. /**
  25691. * Registers a function to be called after every frame render
  25692. * @param func defines the function to register
  25693. */
  25694. Scene.prototype.registerAfterRender = function (func) {
  25695. this.onAfterRenderObservable.add(func);
  25696. };
  25697. /**
  25698. * Unregisters a function called after every frame render
  25699. * @param func defines the function to unregister
  25700. */
  25701. Scene.prototype.unregisterAfterRender = function (func) {
  25702. this.onAfterRenderObservable.removeCallback(func);
  25703. };
  25704. Scene.prototype._executeOnceBeforeRender = function (func) {
  25705. var _this = this;
  25706. var execFunc = function () {
  25707. func();
  25708. setTimeout(function () {
  25709. _this.unregisterBeforeRender(execFunc);
  25710. });
  25711. };
  25712. this.registerBeforeRender(execFunc);
  25713. };
  25714. /**
  25715. * The provided function will run before render once and will be disposed afterwards.
  25716. * A timeout delay can be provided so that the function will be executed in N ms.
  25717. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25718. * @param func The function to be executed.
  25719. * @param timeout optional delay in ms
  25720. */
  25721. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25722. var _this = this;
  25723. if (timeout !== undefined) {
  25724. setTimeout(function () {
  25725. _this._executeOnceBeforeRender(func);
  25726. }, timeout);
  25727. }
  25728. else {
  25729. this._executeOnceBeforeRender(func);
  25730. }
  25731. };
  25732. /** @hidden */
  25733. Scene.prototype._addPendingData = function (data) {
  25734. this._pendingData.push(data);
  25735. };
  25736. /** @hidden */
  25737. Scene.prototype._removePendingData = function (data) {
  25738. var wasLoading = this.isLoading;
  25739. var index = this._pendingData.indexOf(data);
  25740. if (index !== -1) {
  25741. this._pendingData.splice(index, 1);
  25742. }
  25743. if (wasLoading && !this.isLoading) {
  25744. this.onDataLoadedObservable.notifyObservers(this);
  25745. }
  25746. };
  25747. /**
  25748. * Returns the number of items waiting to be loaded
  25749. * @returns the number of items waiting to be loaded
  25750. */
  25751. Scene.prototype.getWaitingItemsCount = function () {
  25752. return this._pendingData.length;
  25753. };
  25754. Object.defineProperty(Scene.prototype, "isLoading", {
  25755. /**
  25756. * Returns a boolean indicating if the scene is still loading data
  25757. */
  25758. get: function () {
  25759. return this._pendingData.length > 0;
  25760. },
  25761. enumerable: true,
  25762. configurable: true
  25763. });
  25764. /**
  25765. * Registers a function to be executed when the scene is ready
  25766. * @param {Function} func - the function to be executed
  25767. */
  25768. Scene.prototype.executeWhenReady = function (func) {
  25769. var _this = this;
  25770. this.onReadyObservable.add(func);
  25771. if (this._executeWhenReadyTimeoutId !== -1) {
  25772. return;
  25773. }
  25774. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25775. _this._checkIsReady();
  25776. }, 150);
  25777. };
  25778. /**
  25779. * Returns a promise that resolves when the scene is ready
  25780. * @returns A promise that resolves when the scene is ready
  25781. */
  25782. Scene.prototype.whenReadyAsync = function () {
  25783. var _this = this;
  25784. return new Promise(function (resolve) {
  25785. _this.executeWhenReady(function () {
  25786. resolve();
  25787. });
  25788. });
  25789. };
  25790. /** @hidden */
  25791. Scene.prototype._checkIsReady = function () {
  25792. var _this = this;
  25793. this._registerTransientComponents();
  25794. if (this.isReady()) {
  25795. this.onReadyObservable.notifyObservers(this);
  25796. this.onReadyObservable.clear();
  25797. this._executeWhenReadyTimeoutId = -1;
  25798. return;
  25799. }
  25800. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25801. _this._checkIsReady();
  25802. }, 150);
  25803. };
  25804. // Animations
  25805. /**
  25806. * Will start the animation sequence of a given target
  25807. * @param target defines the target
  25808. * @param from defines from which frame should animation start
  25809. * @param to defines until which frame should animation run.
  25810. * @param weight defines the weight to apply to the animation (1.0 by default)
  25811. * @param loop defines if the animation loops
  25812. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25813. * @param onAnimationEnd defines the function to be executed when the animation ends
  25814. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25815. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25816. * @returns the animatable object created for this animation
  25817. */
  25818. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25819. if (weight === void 0) { weight = 1.0; }
  25820. if (speedRatio === void 0) { speedRatio = 1.0; }
  25821. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25822. returnedAnimatable.weight = weight;
  25823. return returnedAnimatable;
  25824. };
  25825. /**
  25826. * Will start the animation sequence of a given target
  25827. * @param target defines the target
  25828. * @param from defines from which frame should animation start
  25829. * @param to defines until which frame should animation run.
  25830. * @param loop defines if the animation loops
  25831. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25832. * @param onAnimationEnd defines the function to be executed when the animation ends
  25833. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25834. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25835. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25836. * @returns the animatable object created for this animation
  25837. */
  25838. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25839. if (speedRatio === void 0) { speedRatio = 1.0; }
  25840. if (stopCurrent === void 0) { stopCurrent = true; }
  25841. if (from > to && speedRatio > 0) {
  25842. speedRatio *= -1;
  25843. }
  25844. if (stopCurrent) {
  25845. this.stopAnimation(target, undefined, targetMask);
  25846. }
  25847. if (!animatable) {
  25848. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25849. }
  25850. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25851. // Local animations
  25852. if (target.animations && shouldRunTargetAnimations) {
  25853. animatable.appendAnimations(target, target.animations);
  25854. }
  25855. // Children animations
  25856. if (target.getAnimatables) {
  25857. var animatables = target.getAnimatables();
  25858. for (var index = 0; index < animatables.length; index++) {
  25859. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25860. }
  25861. }
  25862. animatable.reset();
  25863. return animatable;
  25864. };
  25865. /**
  25866. * Begin a new animation on a given node
  25867. * @param target defines the target where the animation will take place
  25868. * @param animations defines the list of animations to start
  25869. * @param from defines the initial value
  25870. * @param to defines the final value
  25871. * @param loop defines if you want animation to loop (off by default)
  25872. * @param speedRatio defines the speed ratio to apply to all animations
  25873. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25874. * @returns the list of created animatables
  25875. */
  25876. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25877. if (speedRatio === undefined) {
  25878. speedRatio = 1.0;
  25879. }
  25880. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25881. return animatable;
  25882. };
  25883. /**
  25884. * Begin a new animation on a given node and its hierarchy
  25885. * @param target defines the root node where the animation will take place
  25886. * @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.
  25887. * @param animations defines the list of animations to start
  25888. * @param from defines the initial value
  25889. * @param to defines the final value
  25890. * @param loop defines if you want animation to loop (off by default)
  25891. * @param speedRatio defines the speed ratio to apply to all animations
  25892. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25893. * @returns the list of animatables created for all nodes
  25894. */
  25895. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25896. var children = target.getDescendants(directDescendantsOnly);
  25897. var result = [];
  25898. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25899. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25900. var child = children_1[_i];
  25901. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25902. }
  25903. return result;
  25904. };
  25905. /**
  25906. * Gets the animatable associated with a specific target
  25907. * @param target defines the target of the animatable
  25908. * @returns the required animatable if found
  25909. */
  25910. Scene.prototype.getAnimatableByTarget = function (target) {
  25911. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25912. if (this._activeAnimatables[index].target === target) {
  25913. return this._activeAnimatables[index];
  25914. }
  25915. }
  25916. return null;
  25917. };
  25918. /**
  25919. * Gets all animatables associated with a given target
  25920. * @param target defines the target to look animatables for
  25921. * @returns an array of Animatables
  25922. */
  25923. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25924. var result = [];
  25925. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25926. if (this._activeAnimatables[index].target === target) {
  25927. result.push(this._activeAnimatables[index]);
  25928. }
  25929. }
  25930. return result;
  25931. };
  25932. Object.defineProperty(Scene.prototype, "animatables", {
  25933. /**
  25934. * Gets all animatable attached to the scene
  25935. */
  25936. get: function () {
  25937. return this._activeAnimatables;
  25938. },
  25939. enumerable: true,
  25940. configurable: true
  25941. });
  25942. /**
  25943. * Will stop the animation of the given target
  25944. * @param target - the target
  25945. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25946. * @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)
  25947. */
  25948. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25949. var animatables = this.getAllAnimatablesByTarget(target);
  25950. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25951. var animatable = animatables_1[_i];
  25952. animatable.stop(animationName, targetMask);
  25953. }
  25954. };
  25955. /**
  25956. * Stops and removes all animations that have been applied to the scene
  25957. */
  25958. Scene.prototype.stopAllAnimations = function () {
  25959. if (this._activeAnimatables) {
  25960. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25961. this._activeAnimatables[i].stop();
  25962. }
  25963. this._activeAnimatables = [];
  25964. }
  25965. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25966. var group = _a[_i];
  25967. group.stop();
  25968. }
  25969. };
  25970. Scene.prototype._animate = function () {
  25971. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25972. return;
  25973. }
  25974. // Getting time
  25975. var now = BABYLON.Tools.Now;
  25976. if (!this._animationTimeLast) {
  25977. if (this._pendingData.length > 0) {
  25978. return;
  25979. }
  25980. this._animationTimeLast = now;
  25981. }
  25982. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25983. this._animationTime += deltaTime;
  25984. this._animationTimeLast = now;
  25985. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25986. this._activeAnimatables[index]._animate(this._animationTime);
  25987. }
  25988. // Late animation bindings
  25989. this._processLateAnimationBindings();
  25990. };
  25991. /** @hidden */
  25992. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25993. var target = runtimeAnimation.target;
  25994. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25995. if (!target._lateAnimationHolders) {
  25996. target._lateAnimationHolders = {};
  25997. }
  25998. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25999. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26000. totalWeight: 0,
  26001. animations: [],
  26002. originalValue: originalValue
  26003. };
  26004. }
  26005. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26006. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26007. };
  26008. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26009. var normalizer = 1.0;
  26010. var finalPosition = BABYLON.Tmp.Vector3[0];
  26011. var finalScaling = BABYLON.Tmp.Vector3[1];
  26012. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26013. var startIndex = 0;
  26014. var originalAnimation = holder.animations[0];
  26015. var originalValue = holder.originalValue;
  26016. var scale = 1;
  26017. if (holder.totalWeight < 1.0) {
  26018. // We need to mix the original value in
  26019. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26020. scale = 1.0 - holder.totalWeight;
  26021. }
  26022. else {
  26023. startIndex = 1;
  26024. // We need to normalize the weights
  26025. normalizer = holder.totalWeight;
  26026. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26027. scale = originalAnimation.weight / normalizer;
  26028. if (scale == 1) {
  26029. return originalAnimation.currentValue;
  26030. }
  26031. }
  26032. finalScaling.scaleInPlace(scale);
  26033. finalPosition.scaleInPlace(scale);
  26034. finalQuaternion.scaleInPlace(scale);
  26035. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26036. var runtimeAnimation = holder.animations[animIndex];
  26037. var scale = runtimeAnimation.weight / normalizer;
  26038. var currentPosition = BABYLON.Tmp.Vector3[2];
  26039. var currentScaling = BABYLON.Tmp.Vector3[3];
  26040. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26041. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26042. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26043. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26044. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26045. }
  26046. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26047. return originalAnimation._workValue;
  26048. };
  26049. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26050. var originalAnimation = holder.animations[0];
  26051. var originalValue = holder.originalValue;
  26052. if (holder.animations.length === 1) {
  26053. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26054. }
  26055. var normalizer = 1.0;
  26056. var quaternions;
  26057. var weights;
  26058. if (holder.totalWeight < 1.0) {
  26059. var scale = 1.0 - holder.totalWeight;
  26060. quaternions = [];
  26061. weights = [];
  26062. quaternions.push(originalValue);
  26063. weights.push(scale);
  26064. }
  26065. else {
  26066. if (holder.animations.length === 2) { // Slerp as soon as we can
  26067. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26068. }
  26069. quaternions = [];
  26070. weights = [];
  26071. normalizer = holder.totalWeight;
  26072. }
  26073. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26074. var runtimeAnimation = holder.animations[animIndex];
  26075. quaternions.push(runtimeAnimation.currentValue);
  26076. weights.push(runtimeAnimation.weight / normalizer);
  26077. }
  26078. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26079. var cumulativeAmount = 0;
  26080. var cumulativeQuaternion = null;
  26081. for (var index = 0; index < quaternions.length;) {
  26082. if (!cumulativeQuaternion) {
  26083. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26084. cumulativeAmount = weights[index] + weights[index + 1];
  26085. index += 2;
  26086. continue;
  26087. }
  26088. cumulativeAmount += weights[index];
  26089. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26090. index++;
  26091. }
  26092. return cumulativeQuaternion;
  26093. };
  26094. Scene.prototype._processLateAnimationBindings = function () {
  26095. if (!this._registeredForLateAnimationBindings.length) {
  26096. return;
  26097. }
  26098. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26099. var target = this._registeredForLateAnimationBindings.data[index];
  26100. for (var path in target._lateAnimationHolders) {
  26101. var holder = target._lateAnimationHolders[path];
  26102. var originalAnimation = holder.animations[0];
  26103. var originalValue = holder.originalValue;
  26104. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26105. var finalValue = void 0;
  26106. if (matrixDecomposeMode) {
  26107. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26108. }
  26109. else {
  26110. var quaternionMode = originalValue.w !== undefined;
  26111. if (quaternionMode) {
  26112. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26113. }
  26114. else {
  26115. var startIndex = 0;
  26116. var normalizer = 1.0;
  26117. if (holder.totalWeight < 1.0) {
  26118. // We need to mix the original value in
  26119. if (originalValue.scale) {
  26120. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26121. }
  26122. else {
  26123. finalValue = originalValue * (1.0 - holder.totalWeight);
  26124. }
  26125. }
  26126. else {
  26127. // We need to normalize the weights
  26128. normalizer = holder.totalWeight;
  26129. var scale_1 = originalAnimation.weight / normalizer;
  26130. if (scale_1 !== 1) {
  26131. if (originalAnimation.currentValue.scale) {
  26132. finalValue = originalAnimation.currentValue.scale(scale_1);
  26133. }
  26134. else {
  26135. finalValue = originalAnimation.currentValue * scale_1;
  26136. }
  26137. }
  26138. else {
  26139. finalValue = originalAnimation.currentValue;
  26140. }
  26141. startIndex = 1;
  26142. }
  26143. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26144. var runtimeAnimation = holder.animations[animIndex];
  26145. var scale = runtimeAnimation.weight / normalizer;
  26146. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26147. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26148. }
  26149. else {
  26150. finalValue += runtimeAnimation.currentValue * scale;
  26151. }
  26152. }
  26153. }
  26154. }
  26155. target[path] = finalValue;
  26156. }
  26157. target._lateAnimationHolders = {};
  26158. }
  26159. this._registeredForLateAnimationBindings.reset();
  26160. };
  26161. // Matrix
  26162. /** @hidden */
  26163. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26164. this._useAlternateCameraConfiguration = active;
  26165. };
  26166. /**
  26167. * Gets the current view matrix
  26168. * @returns a Matrix
  26169. */
  26170. Scene.prototype.getViewMatrix = function () {
  26171. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26172. };
  26173. /**
  26174. * Gets the current projection matrix
  26175. * @returns a Matrix
  26176. */
  26177. Scene.prototype.getProjectionMatrix = function () {
  26178. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26179. };
  26180. /**
  26181. * Gets the current transform matrix
  26182. * @returns a Matrix made of View * Projection
  26183. */
  26184. Scene.prototype.getTransformMatrix = function () {
  26185. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26186. };
  26187. /**
  26188. * Sets the current transform matrix
  26189. * @param view defines the View matrix to use
  26190. * @param projection defines the Projection matrix to use
  26191. */
  26192. Scene.prototype.setTransformMatrix = function (view, projection) {
  26193. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26194. return;
  26195. }
  26196. this._viewUpdateFlag = view.updateFlag;
  26197. this._projectionUpdateFlag = projection.updateFlag;
  26198. this._viewMatrix = view;
  26199. this._projectionMatrix = projection;
  26200. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26201. // Update frustum
  26202. if (!this._frustumPlanes) {
  26203. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26204. }
  26205. else {
  26206. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26207. }
  26208. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26209. var otherCamera = this.activeCamera._alternateCamera;
  26210. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26211. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26212. }
  26213. if (this._sceneUbo.useUbo) {
  26214. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26215. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26216. this._sceneUbo.update();
  26217. }
  26218. };
  26219. /** @hidden */
  26220. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26221. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26222. return;
  26223. }
  26224. this._alternateViewUpdateFlag = view.updateFlag;
  26225. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26226. this._alternateViewMatrix = view;
  26227. this._alternateProjectionMatrix = projection;
  26228. if (!this._alternateTransformMatrix) {
  26229. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26230. }
  26231. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26232. if (!this._alternateSceneUbo) {
  26233. this._createAlternateUbo();
  26234. }
  26235. if (this._alternateSceneUbo.useUbo) {
  26236. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26237. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26238. this._alternateSceneUbo.update();
  26239. }
  26240. };
  26241. /**
  26242. * Gets the uniform buffer used to store scene data
  26243. * @returns a UniformBuffer
  26244. */
  26245. Scene.prototype.getSceneUniformBuffer = function () {
  26246. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26247. };
  26248. /**
  26249. * Gets an unique (relatively to the current scene) Id
  26250. * @returns an unique number for the scene
  26251. */
  26252. Scene.prototype.getUniqueId = function () {
  26253. var result = Scene._uniqueIdCounter;
  26254. Scene._uniqueIdCounter++;
  26255. return result;
  26256. };
  26257. /**
  26258. * Add a mesh to the list of scene's meshes
  26259. * @param newMesh defines the mesh to add
  26260. * @param recursive if all child meshes should also be added to the scene
  26261. */
  26262. Scene.prototype.addMesh = function (newMesh, recursive) {
  26263. var _this = this;
  26264. if (recursive === void 0) { recursive = false; }
  26265. this.meshes.push(newMesh);
  26266. //notify the collision coordinator
  26267. if (this.collisionCoordinator) {
  26268. this.collisionCoordinator.onMeshAdded(newMesh);
  26269. }
  26270. newMesh._resyncLightSources();
  26271. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26272. if (recursive) {
  26273. newMesh.getChildMeshes().forEach(function (m) {
  26274. _this.addMesh(m);
  26275. });
  26276. }
  26277. };
  26278. /**
  26279. * Remove a mesh for the list of scene's meshes
  26280. * @param toRemove defines the mesh to remove
  26281. * @param recursive if all child meshes should also be removed from the scene
  26282. * @returns the index where the mesh was in the mesh list
  26283. */
  26284. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26285. var _this = this;
  26286. if (recursive === void 0) { recursive = false; }
  26287. var index = this.meshes.indexOf(toRemove);
  26288. if (index !== -1) {
  26289. // Remove from the scene if mesh found
  26290. this.meshes.splice(index, 1);
  26291. }
  26292. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26293. if (recursive) {
  26294. toRemove.getChildMeshes().forEach(function (m) {
  26295. _this.removeMesh(m);
  26296. });
  26297. }
  26298. return index;
  26299. };
  26300. /**
  26301. * Add a transform node to the list of scene's transform nodes
  26302. * @param newTransformNode defines the transform node to add
  26303. */
  26304. Scene.prototype.addTransformNode = function (newTransformNode) {
  26305. this.transformNodes.push(newTransformNode);
  26306. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26307. };
  26308. /**
  26309. * Remove a transform node for the list of scene's transform nodes
  26310. * @param toRemove defines the transform node to remove
  26311. * @returns the index where the transform node was in the transform node list
  26312. */
  26313. Scene.prototype.removeTransformNode = function (toRemove) {
  26314. var index = this.transformNodes.indexOf(toRemove);
  26315. if (index !== -1) {
  26316. // Remove from the scene if found
  26317. this.transformNodes.splice(index, 1);
  26318. }
  26319. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26320. return index;
  26321. };
  26322. /**
  26323. * Remove a skeleton for the list of scene's skeletons
  26324. * @param toRemove defines the skeleton to remove
  26325. * @returns the index where the skeleton was in the skeleton list
  26326. */
  26327. Scene.prototype.removeSkeleton = function (toRemove) {
  26328. var index = this.skeletons.indexOf(toRemove);
  26329. if (index !== -1) {
  26330. // Remove from the scene if found
  26331. this.skeletons.splice(index, 1);
  26332. }
  26333. return index;
  26334. };
  26335. /**
  26336. * Remove a morph target for the list of scene's morph targets
  26337. * @param toRemove defines the morph target to remove
  26338. * @returns the index where the morph target was in the morph target list
  26339. */
  26340. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26341. var index = this.morphTargetManagers.indexOf(toRemove);
  26342. if (index !== -1) {
  26343. // Remove from the scene if found
  26344. this.morphTargetManagers.splice(index, 1);
  26345. }
  26346. return index;
  26347. };
  26348. /**
  26349. * Remove a light for the list of scene's lights
  26350. * @param toRemove defines the light to remove
  26351. * @returns the index where the light was in the light list
  26352. */
  26353. Scene.prototype.removeLight = function (toRemove) {
  26354. var index = this.lights.indexOf(toRemove);
  26355. if (index !== -1) {
  26356. // Remove from meshes
  26357. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26358. var mesh = _a[_i];
  26359. mesh._removeLightSource(toRemove);
  26360. }
  26361. // Remove from the scene if mesh found
  26362. this.lights.splice(index, 1);
  26363. this.sortLightsByPriority();
  26364. }
  26365. this.onLightRemovedObservable.notifyObservers(toRemove);
  26366. return index;
  26367. };
  26368. /**
  26369. * Remove a camera for the list of scene's cameras
  26370. * @param toRemove defines the camera to remove
  26371. * @returns the index where the camera was in the camera list
  26372. */
  26373. Scene.prototype.removeCamera = function (toRemove) {
  26374. var index = this.cameras.indexOf(toRemove);
  26375. if (index !== -1) {
  26376. // Remove from the scene if mesh found
  26377. this.cameras.splice(index, 1);
  26378. }
  26379. // Remove from activeCameras
  26380. var index2 = this.activeCameras.indexOf(toRemove);
  26381. if (index2 !== -1) {
  26382. // Remove from the scene if mesh found
  26383. this.activeCameras.splice(index2, 1);
  26384. }
  26385. // Reset the activeCamera
  26386. if (this.activeCamera === toRemove) {
  26387. if (this.cameras.length > 0) {
  26388. this.activeCamera = this.cameras[0];
  26389. }
  26390. else {
  26391. this.activeCamera = null;
  26392. }
  26393. }
  26394. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26395. return index;
  26396. };
  26397. /**
  26398. * Remove a particle system for the list of scene's particle systems
  26399. * @param toRemove defines the particle system to remove
  26400. * @returns the index where the particle system was in the particle system list
  26401. */
  26402. Scene.prototype.removeParticleSystem = function (toRemove) {
  26403. var index = this.particleSystems.indexOf(toRemove);
  26404. if (index !== -1) {
  26405. this.particleSystems.splice(index, 1);
  26406. }
  26407. return index;
  26408. };
  26409. /**
  26410. * Remove a animation for the list of scene's animations
  26411. * @param toRemove defines the animation to remove
  26412. * @returns the index where the animation was in the animation list
  26413. */
  26414. Scene.prototype.removeAnimation = function (toRemove) {
  26415. var index = this.animations.indexOf(toRemove);
  26416. if (index !== -1) {
  26417. this.animations.splice(index, 1);
  26418. }
  26419. return index;
  26420. };
  26421. /**
  26422. * Removes the given animation group from this scene.
  26423. * @param toRemove The animation group to remove
  26424. * @returns The index of the removed animation group
  26425. */
  26426. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26427. var index = this.animationGroups.indexOf(toRemove);
  26428. if (index !== -1) {
  26429. this.animationGroups.splice(index, 1);
  26430. }
  26431. return index;
  26432. };
  26433. /**
  26434. * Removes the given multi-material from this scene.
  26435. * @param toRemove The multi-material to remove
  26436. * @returns The index of the removed multi-material
  26437. */
  26438. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26439. var index = this.multiMaterials.indexOf(toRemove);
  26440. if (index !== -1) {
  26441. this.multiMaterials.splice(index, 1);
  26442. }
  26443. return index;
  26444. };
  26445. /**
  26446. * Removes the given material from this scene.
  26447. * @param toRemove The material to remove
  26448. * @returns The index of the removed material
  26449. */
  26450. Scene.prototype.removeMaterial = function (toRemove) {
  26451. var index = this.materials.indexOf(toRemove);
  26452. if (index !== -1) {
  26453. this.materials.splice(index, 1);
  26454. }
  26455. return index;
  26456. };
  26457. /**
  26458. * Removes the given action manager from this scene.
  26459. * @param toRemove The action manager to remove
  26460. * @returns The index of the removed action manager
  26461. */
  26462. Scene.prototype.removeActionManager = function (toRemove) {
  26463. var index = this.actionManagers.indexOf(toRemove);
  26464. if (index !== -1) {
  26465. this.actionManagers.splice(index, 1);
  26466. }
  26467. return index;
  26468. };
  26469. /**
  26470. * Removes the given texture from this scene.
  26471. * @param toRemove The texture to remove
  26472. * @returns The index of the removed texture
  26473. */
  26474. Scene.prototype.removeTexture = function (toRemove) {
  26475. var index = this.textures.indexOf(toRemove);
  26476. if (index !== -1) {
  26477. this.textures.splice(index, 1);
  26478. }
  26479. return index;
  26480. };
  26481. /**
  26482. * Adds the given light to this scene
  26483. * @param newLight The light to add
  26484. */
  26485. Scene.prototype.addLight = function (newLight) {
  26486. this.lights.push(newLight);
  26487. this.sortLightsByPriority();
  26488. // Add light to all meshes (To support if the light is removed and then readded)
  26489. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26490. var mesh = _a[_i];
  26491. if (mesh._lightSources.indexOf(newLight) === -1) {
  26492. mesh._lightSources.push(newLight);
  26493. mesh._resyncLightSources();
  26494. }
  26495. }
  26496. this.onNewLightAddedObservable.notifyObservers(newLight);
  26497. };
  26498. /**
  26499. * Sorts the list list based on light priorities
  26500. */
  26501. Scene.prototype.sortLightsByPriority = function () {
  26502. if (this.requireLightSorting) {
  26503. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26504. }
  26505. };
  26506. /**
  26507. * Adds the given camera to this scene
  26508. * @param newCamera The camera to add
  26509. */
  26510. Scene.prototype.addCamera = function (newCamera) {
  26511. this.cameras.push(newCamera);
  26512. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26513. };
  26514. /**
  26515. * Adds the given skeleton to this scene
  26516. * @param newSkeleton The skeleton to add
  26517. */
  26518. Scene.prototype.addSkeleton = function (newSkeleton) {
  26519. this.skeletons.push(newSkeleton);
  26520. };
  26521. /**
  26522. * Adds the given particle system to this scene
  26523. * @param newParticleSystem The particle system to add
  26524. */
  26525. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26526. this.particleSystems.push(newParticleSystem);
  26527. };
  26528. /**
  26529. * Adds the given animation to this scene
  26530. * @param newAnimation The animation to add
  26531. */
  26532. Scene.prototype.addAnimation = function (newAnimation) {
  26533. this.animations.push(newAnimation);
  26534. };
  26535. /**
  26536. * Adds the given animation group to this scene.
  26537. * @param newAnimationGroup The animation group to add
  26538. */
  26539. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26540. this.animationGroups.push(newAnimationGroup);
  26541. };
  26542. /**
  26543. * Adds the given multi-material to this scene
  26544. * @param newMultiMaterial The multi-material to add
  26545. */
  26546. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26547. this.multiMaterials.push(newMultiMaterial);
  26548. };
  26549. /**
  26550. * Adds the given material to this scene
  26551. * @param newMaterial The material to add
  26552. */
  26553. Scene.prototype.addMaterial = function (newMaterial) {
  26554. this.materials.push(newMaterial);
  26555. };
  26556. /**
  26557. * Adds the given morph target to this scene
  26558. * @param newMorphTargetManager The morph target to add
  26559. */
  26560. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26561. this.morphTargetManagers.push(newMorphTargetManager);
  26562. };
  26563. /**
  26564. * Adds the given geometry to this scene
  26565. * @param newGeometry The geometry to add
  26566. */
  26567. Scene.prototype.addGeometry = function (newGeometry) {
  26568. this.geometries.push(newGeometry);
  26569. };
  26570. /**
  26571. * Adds the given action manager to this scene
  26572. * @param newActionManager The action manager to add
  26573. */
  26574. Scene.prototype.addActionManager = function (newActionManager) {
  26575. this.actionManagers.push(newActionManager);
  26576. };
  26577. /**
  26578. * Adds the given texture to this scene.
  26579. * @param newTexture The texture to add
  26580. */
  26581. Scene.prototype.addTexture = function (newTexture) {
  26582. this.textures.push(newTexture);
  26583. };
  26584. /**
  26585. * Switch active camera
  26586. * @param newCamera defines the new active camera
  26587. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26588. */
  26589. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26590. if (attachControl === void 0) { attachControl = true; }
  26591. var canvas = this._engine.getRenderingCanvas();
  26592. if (!canvas) {
  26593. return;
  26594. }
  26595. if (this.activeCamera) {
  26596. this.activeCamera.detachControl(canvas);
  26597. }
  26598. this.activeCamera = newCamera;
  26599. if (attachControl) {
  26600. newCamera.attachControl(canvas);
  26601. }
  26602. };
  26603. /**
  26604. * sets the active camera of the scene using its ID
  26605. * @param id defines the camera's ID
  26606. * @return the new active camera or null if none found.
  26607. */
  26608. Scene.prototype.setActiveCameraByID = function (id) {
  26609. var camera = this.getCameraByID(id);
  26610. if (camera) {
  26611. this.activeCamera = camera;
  26612. return camera;
  26613. }
  26614. return null;
  26615. };
  26616. /**
  26617. * sets the active camera of the scene using its name
  26618. * @param name defines the camera's name
  26619. * @returns the new active camera or null if none found.
  26620. */
  26621. Scene.prototype.setActiveCameraByName = function (name) {
  26622. var camera = this.getCameraByName(name);
  26623. if (camera) {
  26624. this.activeCamera = camera;
  26625. return camera;
  26626. }
  26627. return null;
  26628. };
  26629. /**
  26630. * get an animation group using its name
  26631. * @param name defines the material's name
  26632. * @return the animation group or null if none found.
  26633. */
  26634. Scene.prototype.getAnimationGroupByName = function (name) {
  26635. for (var index = 0; index < this.animationGroups.length; index++) {
  26636. if (this.animationGroups[index].name === name) {
  26637. return this.animationGroups[index];
  26638. }
  26639. }
  26640. return null;
  26641. };
  26642. /**
  26643. * get a material using its id
  26644. * @param id defines the material's ID
  26645. * @return the material or null if none found.
  26646. */
  26647. Scene.prototype.getMaterialByID = function (id) {
  26648. for (var index = 0; index < this.materials.length; index++) {
  26649. if (this.materials[index].id === id) {
  26650. return this.materials[index];
  26651. }
  26652. }
  26653. return null;
  26654. };
  26655. /**
  26656. * Gets a material using its name
  26657. * @param name defines the material's name
  26658. * @return the material or null if none found.
  26659. */
  26660. Scene.prototype.getMaterialByName = function (name) {
  26661. for (var index = 0; index < this.materials.length; index++) {
  26662. if (this.materials[index].name === name) {
  26663. return this.materials[index];
  26664. }
  26665. }
  26666. return null;
  26667. };
  26668. /**
  26669. * Gets a camera using its id
  26670. * @param id defines the id to look for
  26671. * @returns the camera or null if not found
  26672. */
  26673. Scene.prototype.getCameraByID = function (id) {
  26674. for (var index = 0; index < this.cameras.length; index++) {
  26675. if (this.cameras[index].id === id) {
  26676. return this.cameras[index];
  26677. }
  26678. }
  26679. return null;
  26680. };
  26681. /**
  26682. * Gets a camera using its unique id
  26683. * @param uniqueId defines the unique id to look for
  26684. * @returns the camera or null if not found
  26685. */
  26686. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26687. for (var index = 0; index < this.cameras.length; index++) {
  26688. if (this.cameras[index].uniqueId === uniqueId) {
  26689. return this.cameras[index];
  26690. }
  26691. }
  26692. return null;
  26693. };
  26694. /**
  26695. * Gets a camera using its name
  26696. * @param name defines the camera's name
  26697. * @return the camera or null if none found.
  26698. */
  26699. Scene.prototype.getCameraByName = function (name) {
  26700. for (var index = 0; index < this.cameras.length; index++) {
  26701. if (this.cameras[index].name === name) {
  26702. return this.cameras[index];
  26703. }
  26704. }
  26705. return null;
  26706. };
  26707. /**
  26708. * Gets a bone using its id
  26709. * @param id defines the bone's id
  26710. * @return the bone or null if not found
  26711. */
  26712. Scene.prototype.getBoneByID = function (id) {
  26713. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26714. var skeleton = this.skeletons[skeletonIndex];
  26715. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26716. if (skeleton.bones[boneIndex].id === id) {
  26717. return skeleton.bones[boneIndex];
  26718. }
  26719. }
  26720. }
  26721. return null;
  26722. };
  26723. /**
  26724. * Gets a bone using its id
  26725. * @param name defines the bone's name
  26726. * @return the bone or null if not found
  26727. */
  26728. Scene.prototype.getBoneByName = function (name) {
  26729. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26730. var skeleton = this.skeletons[skeletonIndex];
  26731. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26732. if (skeleton.bones[boneIndex].name === name) {
  26733. return skeleton.bones[boneIndex];
  26734. }
  26735. }
  26736. }
  26737. return null;
  26738. };
  26739. /**
  26740. * Gets a light node using its name
  26741. * @param name defines the the light's name
  26742. * @return the light or null if none found.
  26743. */
  26744. Scene.prototype.getLightByName = function (name) {
  26745. for (var index = 0; index < this.lights.length; index++) {
  26746. if (this.lights[index].name === name) {
  26747. return this.lights[index];
  26748. }
  26749. }
  26750. return null;
  26751. };
  26752. /**
  26753. * Gets a light node using its id
  26754. * @param id defines the light's id
  26755. * @return the light or null if none found.
  26756. */
  26757. Scene.prototype.getLightByID = function (id) {
  26758. for (var index = 0; index < this.lights.length; index++) {
  26759. if (this.lights[index].id === id) {
  26760. return this.lights[index];
  26761. }
  26762. }
  26763. return null;
  26764. };
  26765. /**
  26766. * Gets a light node using its scene-generated unique ID
  26767. * @param uniqueId defines the light's unique id
  26768. * @return the light or null if none found.
  26769. */
  26770. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26771. for (var index = 0; index < this.lights.length; index++) {
  26772. if (this.lights[index].uniqueId === uniqueId) {
  26773. return this.lights[index];
  26774. }
  26775. }
  26776. return null;
  26777. };
  26778. /**
  26779. * Gets a particle system by id
  26780. * @param id defines the particle system id
  26781. * @return the corresponding system or null if none found
  26782. */
  26783. Scene.prototype.getParticleSystemByID = function (id) {
  26784. for (var index = 0; index < this.particleSystems.length; index++) {
  26785. if (this.particleSystems[index].id === id) {
  26786. return this.particleSystems[index];
  26787. }
  26788. }
  26789. return null;
  26790. };
  26791. /**
  26792. * Gets a geometry using its ID
  26793. * @param id defines the geometry's id
  26794. * @return the geometry or null if none found.
  26795. */
  26796. Scene.prototype.getGeometryByID = function (id) {
  26797. for (var index = 0; index < this.geometries.length; index++) {
  26798. if (this.geometries[index].id === id) {
  26799. return this.geometries[index];
  26800. }
  26801. }
  26802. return null;
  26803. };
  26804. /**
  26805. * Add a new geometry to this scene
  26806. * @param geometry defines the geometry to be added to the scene.
  26807. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26808. * @return a boolean defining if the geometry was added or not
  26809. */
  26810. Scene.prototype.pushGeometry = function (geometry, force) {
  26811. if (!force && this.getGeometryByID(geometry.id)) {
  26812. return false;
  26813. }
  26814. this.geometries.push(geometry);
  26815. //notify the collision coordinator
  26816. if (this.collisionCoordinator) {
  26817. this.collisionCoordinator.onGeometryAdded(geometry);
  26818. }
  26819. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26820. return true;
  26821. };
  26822. /**
  26823. * Removes an existing geometry
  26824. * @param geometry defines the geometry to be removed from the scene
  26825. * @return a boolean defining if the geometry was removed or not
  26826. */
  26827. Scene.prototype.removeGeometry = function (geometry) {
  26828. var index = this.geometries.indexOf(geometry);
  26829. if (index > -1) {
  26830. this.geometries.splice(index, 1);
  26831. //notify the collision coordinator
  26832. if (this.collisionCoordinator) {
  26833. this.collisionCoordinator.onGeometryDeleted(geometry);
  26834. }
  26835. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26836. return true;
  26837. }
  26838. return false;
  26839. };
  26840. /**
  26841. * Gets the list of geometries attached to the scene
  26842. * @returns an array of Geometry
  26843. */
  26844. Scene.prototype.getGeometries = function () {
  26845. return this.geometries;
  26846. };
  26847. /**
  26848. * Gets the first added mesh found of a given ID
  26849. * @param id defines the id to search for
  26850. * @return the mesh found or null if not found at all
  26851. */
  26852. Scene.prototype.getMeshByID = function (id) {
  26853. for (var index = 0; index < this.meshes.length; index++) {
  26854. if (this.meshes[index].id === id) {
  26855. return this.meshes[index];
  26856. }
  26857. }
  26858. return null;
  26859. };
  26860. /**
  26861. * Gets a list of meshes using their id
  26862. * @param id defines the id to search for
  26863. * @returns a list of meshes
  26864. */
  26865. Scene.prototype.getMeshesByID = function (id) {
  26866. return this.meshes.filter(function (m) {
  26867. return m.id === id;
  26868. });
  26869. };
  26870. /**
  26871. * Gets the first added transform node found of a given ID
  26872. * @param id defines the id to search for
  26873. * @return the found transform node or null if not found at all.
  26874. */
  26875. Scene.prototype.getTransformNodeByID = function (id) {
  26876. for (var index = 0; index < this.transformNodes.length; index++) {
  26877. if (this.transformNodes[index].id === id) {
  26878. return this.transformNodes[index];
  26879. }
  26880. }
  26881. return null;
  26882. };
  26883. /**
  26884. * Gets a list of transform nodes using their id
  26885. * @param id defines the id to search for
  26886. * @returns a list of transform nodes
  26887. */
  26888. Scene.prototype.getTransformNodesByID = function (id) {
  26889. return this.transformNodes.filter(function (m) {
  26890. return m.id === id;
  26891. });
  26892. };
  26893. /**
  26894. * Gets a mesh with its auto-generated unique id
  26895. * @param uniqueId defines the unique id to search for
  26896. * @return the found mesh or null if not found at all.
  26897. */
  26898. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26899. for (var index = 0; index < this.meshes.length; index++) {
  26900. if (this.meshes[index].uniqueId === uniqueId) {
  26901. return this.meshes[index];
  26902. }
  26903. }
  26904. return null;
  26905. };
  26906. /**
  26907. * Gets a the last added mesh using a given id
  26908. * @param id defines the id to search for
  26909. * @return the found mesh or null if not found at all.
  26910. */
  26911. Scene.prototype.getLastMeshByID = function (id) {
  26912. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26913. if (this.meshes[index].id === id) {
  26914. return this.meshes[index];
  26915. }
  26916. }
  26917. return null;
  26918. };
  26919. /**
  26920. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26921. * @param id defines the id to search for
  26922. * @return the found node or null if not found at all
  26923. */
  26924. Scene.prototype.getLastEntryByID = function (id) {
  26925. var index;
  26926. for (index = this.meshes.length - 1; index >= 0; index--) {
  26927. if (this.meshes[index].id === id) {
  26928. return this.meshes[index];
  26929. }
  26930. }
  26931. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26932. if (this.transformNodes[index].id === id) {
  26933. return this.transformNodes[index];
  26934. }
  26935. }
  26936. for (index = this.cameras.length - 1; index >= 0; index--) {
  26937. if (this.cameras[index].id === id) {
  26938. return this.cameras[index];
  26939. }
  26940. }
  26941. for (index = this.lights.length - 1; index >= 0; index--) {
  26942. if (this.lights[index].id === id) {
  26943. return this.lights[index];
  26944. }
  26945. }
  26946. return null;
  26947. };
  26948. /**
  26949. * Gets a node (Mesh, Camera, Light) using a given id
  26950. * @param id defines the id to search for
  26951. * @return the found node or null if not found at all
  26952. */
  26953. Scene.prototype.getNodeByID = function (id) {
  26954. var mesh = this.getMeshByID(id);
  26955. if (mesh) {
  26956. return mesh;
  26957. }
  26958. var light = this.getLightByID(id);
  26959. if (light) {
  26960. return light;
  26961. }
  26962. var camera = this.getCameraByID(id);
  26963. if (camera) {
  26964. return camera;
  26965. }
  26966. var bone = this.getBoneByID(id);
  26967. return bone;
  26968. };
  26969. /**
  26970. * Gets a node (Mesh, Camera, Light) using a given name
  26971. * @param name defines the name to search for
  26972. * @return the found node or null if not found at all.
  26973. */
  26974. Scene.prototype.getNodeByName = function (name) {
  26975. var mesh = this.getMeshByName(name);
  26976. if (mesh) {
  26977. return mesh;
  26978. }
  26979. var light = this.getLightByName(name);
  26980. if (light) {
  26981. return light;
  26982. }
  26983. var camera = this.getCameraByName(name);
  26984. if (camera) {
  26985. return camera;
  26986. }
  26987. var bone = this.getBoneByName(name);
  26988. return bone;
  26989. };
  26990. /**
  26991. * Gets a mesh using a given name
  26992. * @param name defines the name to search for
  26993. * @return the found mesh or null if not found at all.
  26994. */
  26995. Scene.prototype.getMeshByName = function (name) {
  26996. for (var index = 0; index < this.meshes.length; index++) {
  26997. if (this.meshes[index].name === name) {
  26998. return this.meshes[index];
  26999. }
  27000. }
  27001. return null;
  27002. };
  27003. /**
  27004. * Gets a transform node using a given name
  27005. * @param name defines the name to search for
  27006. * @return the found transform node or null if not found at all.
  27007. */
  27008. Scene.prototype.getTransformNodeByName = function (name) {
  27009. for (var index = 0; index < this.transformNodes.length; index++) {
  27010. if (this.transformNodes[index].name === name) {
  27011. return this.transformNodes[index];
  27012. }
  27013. }
  27014. return null;
  27015. };
  27016. /**
  27017. * Gets a sound using a given name
  27018. * @param name defines the name to search for
  27019. * @return the found sound or null if not found at all.
  27020. */
  27021. Scene.prototype.getSoundByName = function (name) {
  27022. var index;
  27023. if (BABYLON.AudioEngine) {
  27024. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27025. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27026. return this.mainSoundTrack.soundCollection[index];
  27027. }
  27028. }
  27029. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27030. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27031. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27032. return this.soundTracks[sdIndex].soundCollection[index];
  27033. }
  27034. }
  27035. }
  27036. }
  27037. return null;
  27038. };
  27039. /**
  27040. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27041. * @param id defines the id to search for
  27042. * @return the found skeleton or null if not found at all.
  27043. */
  27044. Scene.prototype.getLastSkeletonByID = function (id) {
  27045. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27046. if (this.skeletons[index].id === id) {
  27047. return this.skeletons[index];
  27048. }
  27049. }
  27050. return null;
  27051. };
  27052. /**
  27053. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27054. * @param id defines the id to search for
  27055. * @return the found skeleton or null if not found at all.
  27056. */
  27057. Scene.prototype.getSkeletonById = function (id) {
  27058. for (var index = 0; index < this.skeletons.length; index++) {
  27059. if (this.skeletons[index].id === id) {
  27060. return this.skeletons[index];
  27061. }
  27062. }
  27063. return null;
  27064. };
  27065. /**
  27066. * Gets a skeleton using a given name
  27067. * @param name defines the name to search for
  27068. * @return the found skeleton or null if not found at all.
  27069. */
  27070. Scene.prototype.getSkeletonByName = function (name) {
  27071. for (var index = 0; index < this.skeletons.length; index++) {
  27072. if (this.skeletons[index].name === name) {
  27073. return this.skeletons[index];
  27074. }
  27075. }
  27076. return null;
  27077. };
  27078. /**
  27079. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27080. * @param id defines the id to search for
  27081. * @return the found morph target manager or null if not found at all.
  27082. */
  27083. Scene.prototype.getMorphTargetManagerById = function (id) {
  27084. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27085. if (this.morphTargetManagers[index].uniqueId === id) {
  27086. return this.morphTargetManagers[index];
  27087. }
  27088. }
  27089. return null;
  27090. };
  27091. /**
  27092. * Gets a boolean indicating if the given mesh is active
  27093. * @param mesh defines the mesh to look for
  27094. * @returns true if the mesh is in the active list
  27095. */
  27096. Scene.prototype.isActiveMesh = function (mesh) {
  27097. return (this._activeMeshes.indexOf(mesh) !== -1);
  27098. };
  27099. Object.defineProperty(Scene.prototype, "uid", {
  27100. /**
  27101. * Return a unique id as a string which can serve as an identifier for the scene
  27102. */
  27103. get: function () {
  27104. if (!this._uid) {
  27105. this._uid = BABYLON.Tools.RandomId();
  27106. }
  27107. return this._uid;
  27108. },
  27109. enumerable: true,
  27110. configurable: true
  27111. });
  27112. /**
  27113. * Add an externaly attached data from its key.
  27114. * This method call will fail and return false, if such key already exists.
  27115. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27116. * @param key the unique key that identifies the data
  27117. * @param data the data object to associate to the key for this Engine instance
  27118. * @return true if no such key were already present and the data was added successfully, false otherwise
  27119. */
  27120. Scene.prototype.addExternalData = function (key, data) {
  27121. if (!this._externalData) {
  27122. this._externalData = new BABYLON.StringDictionary();
  27123. }
  27124. return this._externalData.add(key, data);
  27125. };
  27126. /**
  27127. * Get an externaly attached data from its key
  27128. * @param key the unique key that identifies the data
  27129. * @return the associated data, if present (can be null), or undefined if not present
  27130. */
  27131. Scene.prototype.getExternalData = function (key) {
  27132. if (!this._externalData) {
  27133. return null;
  27134. }
  27135. return this._externalData.get(key);
  27136. };
  27137. /**
  27138. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27139. * @param key the unique key that identifies the data
  27140. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27141. * @return the associated data, can be null if the factory returned null.
  27142. */
  27143. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27144. if (!this._externalData) {
  27145. this._externalData = new BABYLON.StringDictionary();
  27146. }
  27147. return this._externalData.getOrAddWithFactory(key, factory);
  27148. };
  27149. /**
  27150. * Remove an externaly attached data from the Engine instance
  27151. * @param key the unique key that identifies the data
  27152. * @return true if the data was successfully removed, false if it doesn't exist
  27153. */
  27154. Scene.prototype.removeExternalData = function (key) {
  27155. return this._externalData.remove(key);
  27156. };
  27157. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27158. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27159. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27160. var step = _a[_i];
  27161. step.action(mesh, subMesh);
  27162. }
  27163. var material = subMesh.getMaterial();
  27164. if (material !== null && material !== undefined) {
  27165. // Render targets
  27166. if (material.getRenderTargetTextures !== undefined) {
  27167. if (this._processedMaterials.indexOf(material) === -1) {
  27168. this._processedMaterials.push(material);
  27169. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27170. }
  27171. }
  27172. // Dispatch
  27173. this._activeIndices.addCount(subMesh.indexCount, false);
  27174. this._renderingManager.dispatch(subMesh, mesh, material);
  27175. }
  27176. }
  27177. };
  27178. /**
  27179. * Clear the processed materials smart array preventing retention point in material dispose.
  27180. */
  27181. Scene.prototype.freeProcessedMaterials = function () {
  27182. this._processedMaterials.dispose();
  27183. };
  27184. /**
  27185. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27186. */
  27187. Scene.prototype.freeActiveMeshes = function () {
  27188. this._activeMeshes.dispose();
  27189. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27190. this.activeCamera._activeMeshes.dispose();
  27191. }
  27192. if (this.activeCameras) {
  27193. for (var i = 0; i < this.activeCameras.length; i++) {
  27194. var activeCamera = this.activeCameras[i];
  27195. if (activeCamera && activeCamera._activeMeshes) {
  27196. activeCamera._activeMeshes.dispose();
  27197. }
  27198. }
  27199. }
  27200. };
  27201. /**
  27202. * Clear the info related to rendering groups preventing retention points during dispose.
  27203. */
  27204. Scene.prototype.freeRenderingGroups = function () {
  27205. if (this._renderingManager) {
  27206. this._renderingManager.freeRenderingGroups();
  27207. }
  27208. if (this.textures) {
  27209. for (var i = 0; i < this.textures.length; i++) {
  27210. var texture = this.textures[i];
  27211. if (texture && texture.renderList) {
  27212. texture.freeRenderingGroups();
  27213. }
  27214. }
  27215. }
  27216. };
  27217. /** @hidden */
  27218. Scene.prototype._isInIntermediateRendering = function () {
  27219. return this._intermediateRendering;
  27220. };
  27221. /**
  27222. * Defines the current active mesh candidate provider
  27223. * @param provider defines the provider to use
  27224. */
  27225. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27226. this._activeMeshCandidateProvider = provider;
  27227. };
  27228. /**
  27229. * Gets the current active mesh candidate provider
  27230. * @returns the current active mesh candidate provider
  27231. */
  27232. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27233. return this._activeMeshCandidateProvider;
  27234. };
  27235. /**
  27236. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27237. * @returns the current scene
  27238. */
  27239. Scene.prototype.freezeActiveMeshes = function () {
  27240. if (!this.activeCamera) {
  27241. return this;
  27242. }
  27243. if (!this._frustumPlanes) {
  27244. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27245. }
  27246. this._evaluateActiveMeshes();
  27247. this._activeMeshesFrozen = true;
  27248. return this;
  27249. };
  27250. /**
  27251. * Use this function to restart evaluating active meshes on every frame
  27252. * @returns the current scene
  27253. */
  27254. Scene.prototype.unfreezeActiveMeshes = function () {
  27255. this._activeMeshesFrozen = false;
  27256. return this;
  27257. };
  27258. Scene.prototype._evaluateActiveMeshes = function () {
  27259. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27260. return;
  27261. }
  27262. if (!this.activeCamera) {
  27263. return;
  27264. }
  27265. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27266. this.activeCamera._activeMeshes.reset();
  27267. this._activeMeshes.reset();
  27268. this._renderingManager.reset();
  27269. this._processedMaterials.reset();
  27270. this._activeParticleSystems.reset();
  27271. this._activeSkeletons.reset();
  27272. this._softwareSkinnedMeshes.reset();
  27273. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27274. var step = _a[_i];
  27275. step.action();
  27276. }
  27277. // Meshes
  27278. var meshes;
  27279. var len;
  27280. var checkIsEnabled = true;
  27281. // Determine mesh candidates
  27282. if (this._activeMeshCandidateProvider !== undefined) {
  27283. // Use _activeMeshCandidateProvider
  27284. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27285. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27286. if (meshes !== undefined) {
  27287. len = meshes.length;
  27288. }
  27289. else {
  27290. len = 0;
  27291. }
  27292. }
  27293. else if (this._selectionOctree !== undefined) {
  27294. // Octree
  27295. var selection = this._selectionOctree.select(this._frustumPlanes);
  27296. meshes = selection.data;
  27297. len = selection.length;
  27298. }
  27299. else {
  27300. // Full scene traversal
  27301. len = this.meshes.length;
  27302. meshes = this.meshes;
  27303. }
  27304. // Check each mesh
  27305. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27306. mesh = meshes[meshIndex];
  27307. if (mesh.isBlocked) {
  27308. continue;
  27309. }
  27310. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27311. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27312. continue;
  27313. }
  27314. mesh.computeWorldMatrix();
  27315. // Intersections
  27316. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27317. this._meshesForIntersections.pushNoDuplicate(mesh);
  27318. }
  27319. // Switch to current LOD
  27320. meshLOD = mesh.getLOD(this.activeCamera);
  27321. if (meshLOD === undefined || meshLOD === null) {
  27322. continue;
  27323. }
  27324. mesh._preActivate();
  27325. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27326. this._activeMeshes.push(mesh);
  27327. this.activeCamera._activeMeshes.push(mesh);
  27328. mesh._activate(this._renderId);
  27329. if (meshLOD !== mesh) {
  27330. meshLOD._activate(this._renderId);
  27331. }
  27332. this._activeMesh(mesh, meshLOD);
  27333. }
  27334. }
  27335. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27336. // Particle systems
  27337. if (this.particlesEnabled) {
  27338. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27339. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27340. var particleSystem = this.particleSystems[particleIndex];
  27341. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27342. continue;
  27343. }
  27344. var emitter = particleSystem.emitter;
  27345. if (!emitter.position || emitter.isEnabled()) {
  27346. this._activeParticleSystems.push(particleSystem);
  27347. particleSystem.animate();
  27348. this._renderingManager.dispatchParticles(particleSystem);
  27349. }
  27350. }
  27351. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27352. }
  27353. };
  27354. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27355. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27356. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27357. mesh.skeleton.prepare();
  27358. }
  27359. if (!mesh.computeBonesUsingShaders) {
  27360. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27361. }
  27362. }
  27363. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27364. var step = _a[_i];
  27365. step.action(sourceMesh, mesh);
  27366. }
  27367. if (mesh !== undefined && mesh !== null
  27368. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27369. // Submeshes Octrees
  27370. var len;
  27371. var subMeshes;
  27372. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27373. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27374. len = intersections.length;
  27375. subMeshes = intersections.data;
  27376. }
  27377. else {
  27378. subMeshes = mesh.subMeshes;
  27379. len = subMeshes.length;
  27380. }
  27381. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27382. subMesh = subMeshes[subIndex];
  27383. this._evaluateSubMesh(subMesh, mesh);
  27384. }
  27385. }
  27386. };
  27387. /**
  27388. * Update the transform matrix to update from the current active camera
  27389. * @param force defines a boolean used to force the update even if cache is up to date
  27390. */
  27391. Scene.prototype.updateTransformMatrix = function (force) {
  27392. if (!this.activeCamera) {
  27393. return;
  27394. }
  27395. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27396. };
  27397. /**
  27398. * 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)
  27399. * @param alternateCamera defines the camera to use
  27400. */
  27401. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27402. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27403. };
  27404. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27405. if (camera && camera._skipRendering) {
  27406. return;
  27407. }
  27408. var engine = this._engine;
  27409. this.activeCamera = camera;
  27410. if (!this.activeCamera)
  27411. throw new Error("Active camera not set");
  27412. // Viewport
  27413. engine.setViewport(this.activeCamera.viewport);
  27414. // Camera
  27415. this.resetCachedMaterial();
  27416. this._renderId++;
  27417. this.updateTransformMatrix();
  27418. if (camera._alternateCamera) {
  27419. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27420. this._alternateRendering = true;
  27421. }
  27422. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27423. // Meshes
  27424. this._evaluateActiveMeshes();
  27425. // Software skinning
  27426. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27427. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27428. mesh.applySkeleton(mesh.skeleton);
  27429. }
  27430. // Render targets
  27431. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27432. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27433. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27434. }
  27435. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27436. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27437. }
  27438. if (this.renderTargetsEnabled) {
  27439. this._intermediateRendering = true;
  27440. if (this._renderTargets.length > 0) {
  27441. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27442. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27443. var renderTarget = this._renderTargets.data[renderIndex];
  27444. if (renderTarget._shouldRender()) {
  27445. this._renderId++;
  27446. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27447. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27448. }
  27449. }
  27450. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27451. this._renderId++;
  27452. }
  27453. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27454. var step = _a[_i];
  27455. step.action(this.activeCamera);
  27456. }
  27457. this._intermediateRendering = false;
  27458. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27459. }
  27460. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27461. // Prepare Frame
  27462. if (this.postProcessManager) {
  27463. this.postProcessManager._prepareFrame();
  27464. }
  27465. // Before Camera Draw
  27466. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27467. var step = _c[_b];
  27468. step.action(this.activeCamera);
  27469. }
  27470. // Render
  27471. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27472. this._renderingManager.render(null, null, true, true);
  27473. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27474. // After Camera Draw
  27475. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27476. var step = _e[_d];
  27477. step.action(this.activeCamera);
  27478. }
  27479. // Finalize frame
  27480. if (this.postProcessManager) {
  27481. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27482. }
  27483. // Reset some special arrays
  27484. this._renderTargets.reset();
  27485. this._alternateRendering = false;
  27486. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27487. };
  27488. Scene.prototype._processSubCameras = function (camera) {
  27489. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27490. this._renderForCamera(camera);
  27491. return;
  27492. }
  27493. // rig cameras
  27494. for (var index = 0; index < camera._rigCameras.length; index++) {
  27495. this._renderForCamera(camera._rigCameras[index], camera);
  27496. }
  27497. this.activeCamera = camera;
  27498. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27499. };
  27500. Scene.prototype._checkIntersections = function () {
  27501. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27502. var sourceMesh = this._meshesForIntersections.data[index];
  27503. if (!sourceMesh.actionManager) {
  27504. continue;
  27505. }
  27506. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27507. var action = sourceMesh.actionManager.actions[actionIndex];
  27508. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27509. var parameters = action.getTriggerParameter();
  27510. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27511. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27512. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27513. if (areIntersecting && currentIntersectionInProgress === -1) {
  27514. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27515. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27516. sourceMesh._intersectionsInProgress.push(otherMesh);
  27517. }
  27518. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27519. sourceMesh._intersectionsInProgress.push(otherMesh);
  27520. }
  27521. }
  27522. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27523. //They intersected, and now they don't.
  27524. //is this trigger an exit trigger? execute an event.
  27525. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27526. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27527. }
  27528. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27529. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27530. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27531. return otherMesh === parameterMesh;
  27532. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27533. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27534. }
  27535. }
  27536. }
  27537. }
  27538. }
  27539. };
  27540. /**
  27541. * Render the scene
  27542. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27543. */
  27544. Scene.prototype.render = function (updateCameras) {
  27545. if (updateCameras === void 0) { updateCameras = true; }
  27546. if (this.isDisposed) {
  27547. return;
  27548. }
  27549. // Register components that have been associated lately to the scene.
  27550. this._registerTransientComponents();
  27551. this._activeParticles.fetchNewFrame();
  27552. this._totalVertices.fetchNewFrame();
  27553. this._activeIndices.fetchNewFrame();
  27554. this._activeBones.fetchNewFrame();
  27555. this._meshesForIntersections.reset();
  27556. this.resetCachedMaterial();
  27557. this.onBeforeAnimationsObservable.notifyObservers(this);
  27558. // Actions
  27559. if (this.actionManager) {
  27560. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27561. }
  27562. //Simplification Queue
  27563. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27564. this.simplificationQueue.executeNext();
  27565. }
  27566. if (this._engine.isDeterministicLockStep()) {
  27567. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27568. var defaultFPS = (60.0 / 1000.0);
  27569. var defaultFrameTime = 1000 / 60; // frame time in MS
  27570. if (this._physicsEngine) {
  27571. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27572. }
  27573. var stepsTaken = 0;
  27574. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27575. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27576. internalSteps = Math.min(internalSteps, maxSubSteps);
  27577. do {
  27578. this.onBeforeStepObservable.notifyObservers(this);
  27579. // Animations
  27580. this._animationRatio = defaultFrameTime * defaultFPS;
  27581. this._animate();
  27582. this.onAfterAnimationsObservable.notifyObservers(this);
  27583. // Physics
  27584. if (this._physicsEngine) {
  27585. this.onBeforePhysicsObservable.notifyObservers(this);
  27586. this._physicsEngine._step(defaultFrameTime / 1000);
  27587. this.onAfterPhysicsObservable.notifyObservers(this);
  27588. }
  27589. this.onAfterStepObservable.notifyObservers(this);
  27590. this._currentStepId++;
  27591. stepsTaken++;
  27592. deltaTime -= defaultFrameTime;
  27593. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27594. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27595. }
  27596. else {
  27597. // Animations
  27598. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27599. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27600. this._animate();
  27601. this.onAfterAnimationsObservable.notifyObservers(this);
  27602. // Physics
  27603. if (this._physicsEngine) {
  27604. this.onBeforePhysicsObservable.notifyObservers(this);
  27605. this._physicsEngine._step(deltaTime / 1000.0);
  27606. this.onAfterPhysicsObservable.notifyObservers(this);
  27607. }
  27608. }
  27609. // Before camera update steps
  27610. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27611. var step = _a[_i];
  27612. step.action();
  27613. }
  27614. // Update Cameras
  27615. if (updateCameras) {
  27616. if (this.activeCameras.length > 0) {
  27617. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27618. var camera = this.activeCameras[cameraIndex];
  27619. camera.update();
  27620. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27621. // rig cameras
  27622. for (var index = 0; index < camera._rigCameras.length; index++) {
  27623. camera._rigCameras[index].update();
  27624. }
  27625. }
  27626. }
  27627. }
  27628. else if (this.activeCamera) {
  27629. this.activeCamera.update();
  27630. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27631. // rig cameras
  27632. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27633. this.activeCamera._rigCameras[index].update();
  27634. }
  27635. }
  27636. }
  27637. }
  27638. // Before render
  27639. this.onBeforeRenderObservable.notifyObservers(this);
  27640. // Customs render targets
  27641. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27642. var engine = this.getEngine();
  27643. var currentActiveCamera = this.activeCamera;
  27644. if (this.renderTargetsEnabled) {
  27645. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27646. this._intermediateRendering = true;
  27647. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27648. var renderTarget = this.customRenderTargets[customIndex];
  27649. if (renderTarget._shouldRender()) {
  27650. this._renderId++;
  27651. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27652. if (!this.activeCamera)
  27653. throw new Error("Active camera not set");
  27654. // Viewport
  27655. engine.setViewport(this.activeCamera.viewport);
  27656. // Camera
  27657. this.updateTransformMatrix();
  27658. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27659. }
  27660. }
  27661. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27662. this._intermediateRendering = false;
  27663. this._renderId++;
  27664. }
  27665. // Restore back buffer
  27666. if (this.customRenderTargets.length > 0) {
  27667. engine.restoreDefaultFramebuffer();
  27668. }
  27669. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27670. this.activeCamera = currentActiveCamera;
  27671. // Procedural textures
  27672. if (this.proceduralTexturesEnabled) {
  27673. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27674. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27675. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27676. if (proceduralTexture._shouldRender()) {
  27677. proceduralTexture.render();
  27678. }
  27679. }
  27680. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27681. }
  27682. // Clear
  27683. if (this.autoClearDepthAndStencil || this.autoClear) {
  27684. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27685. }
  27686. // Shadows
  27687. if (this.shadowsEnabled) {
  27688. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27689. var light = this.lights[lightIndex];
  27690. var shadowGenerator = light.getShadowGenerator();
  27691. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27692. var shadowMap = (shadowGenerator.getShadowMap());
  27693. if (this.textures.indexOf(shadowMap) !== -1) {
  27694. this._renderTargets.push(shadowMap);
  27695. }
  27696. }
  27697. }
  27698. }
  27699. // Depth renderer
  27700. for (var key in this._depthRenderer) {
  27701. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27702. }
  27703. // Geometry renderer
  27704. if (this._geometryBufferRenderer) {
  27705. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27706. }
  27707. // RenderPipeline
  27708. if (this._postProcessRenderPipelineManager) {
  27709. this._postProcessRenderPipelineManager.update();
  27710. }
  27711. // Multi-cameras?
  27712. if (this.activeCameras.length > 0) {
  27713. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27714. if (cameraIndex > 0) {
  27715. this._engine.clear(null, false, true, true);
  27716. }
  27717. this._processSubCameras(this.activeCameras[cameraIndex]);
  27718. }
  27719. }
  27720. else {
  27721. if (!this.activeCamera) {
  27722. throw new Error("No camera defined");
  27723. }
  27724. this._processSubCameras(this.activeCamera);
  27725. }
  27726. // Intersection checks
  27727. this._checkIntersections();
  27728. // Update the audio listener attached to the camera
  27729. if (BABYLON.AudioEngine) {
  27730. this._updateAudioParameters();
  27731. }
  27732. // After render
  27733. if (this.afterRender) {
  27734. this.afterRender();
  27735. }
  27736. this.onAfterRenderObservable.notifyObservers(this);
  27737. // Cleaning
  27738. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27739. var data = this._toBeDisposed.data[index];
  27740. if (data) {
  27741. data.dispose();
  27742. }
  27743. this._toBeDisposed[index] = null;
  27744. }
  27745. this._toBeDisposed.reset();
  27746. if (this.dumpNextRenderTargets) {
  27747. this.dumpNextRenderTargets = false;
  27748. }
  27749. this._activeBones.addCount(0, true);
  27750. this._activeIndices.addCount(0, true);
  27751. this._activeParticles.addCount(0, true);
  27752. };
  27753. Scene.prototype._updateAudioParameters = function () {
  27754. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27755. return;
  27756. }
  27757. var listeningCamera;
  27758. var audioEngine = BABYLON.Engine.audioEngine;
  27759. if (this.activeCameras.length > 0) {
  27760. listeningCamera = this.activeCameras[0];
  27761. }
  27762. else {
  27763. listeningCamera = this.activeCamera;
  27764. }
  27765. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27766. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27767. // for VR cameras
  27768. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27769. listeningCamera = listeningCamera.rigCameras[0];
  27770. }
  27771. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27772. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27773. cameraDirection.normalize();
  27774. // To avoid some errors on GearVR
  27775. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27776. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27777. }
  27778. var i;
  27779. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27780. var sound = this.mainSoundTrack.soundCollection[i];
  27781. if (sound.useCustomAttenuation) {
  27782. sound.updateDistanceFromListener();
  27783. }
  27784. }
  27785. for (i = 0; i < this.soundTracks.length; i++) {
  27786. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27787. sound = this.soundTracks[i].soundCollection[j];
  27788. if (sound.useCustomAttenuation) {
  27789. sound.updateDistanceFromListener();
  27790. }
  27791. }
  27792. }
  27793. }
  27794. };
  27795. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27796. // Audio
  27797. /**
  27798. * Gets or sets if audio support is enabled
  27799. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27800. */
  27801. get: function () {
  27802. return this._audioEnabled;
  27803. },
  27804. set: function (value) {
  27805. this._audioEnabled = value;
  27806. if (BABYLON.AudioEngine) {
  27807. if (this._audioEnabled) {
  27808. this._enableAudio();
  27809. }
  27810. else {
  27811. this._disableAudio();
  27812. }
  27813. }
  27814. },
  27815. enumerable: true,
  27816. configurable: true
  27817. });
  27818. Scene.prototype._disableAudio = function () {
  27819. var i;
  27820. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27821. this.mainSoundTrack.soundCollection[i].pause();
  27822. }
  27823. for (i = 0; i < this.soundTracks.length; i++) {
  27824. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27825. this.soundTracks[i].soundCollection[j].pause();
  27826. }
  27827. }
  27828. };
  27829. Scene.prototype._enableAudio = function () {
  27830. var i;
  27831. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27832. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27833. this.mainSoundTrack.soundCollection[i].play();
  27834. }
  27835. }
  27836. for (i = 0; i < this.soundTracks.length; i++) {
  27837. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27838. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27839. this.soundTracks[i].soundCollection[j].play();
  27840. }
  27841. }
  27842. }
  27843. };
  27844. Object.defineProperty(Scene.prototype, "headphone", {
  27845. /**
  27846. * Gets or sets if audio will be output to headphones
  27847. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27848. */
  27849. get: function () {
  27850. return this._headphone;
  27851. },
  27852. set: function (value) {
  27853. this._headphone = value;
  27854. if (BABYLON.AudioEngine) {
  27855. if (this._headphone) {
  27856. this._switchAudioModeForHeadphones();
  27857. }
  27858. else {
  27859. this._switchAudioModeForNormalSpeakers();
  27860. }
  27861. }
  27862. },
  27863. enumerable: true,
  27864. configurable: true
  27865. });
  27866. Scene.prototype._switchAudioModeForHeadphones = function () {
  27867. this.mainSoundTrack.switchPanningModelToHRTF();
  27868. for (var i = 0; i < this.soundTracks.length; i++) {
  27869. this.soundTracks[i].switchPanningModelToHRTF();
  27870. }
  27871. };
  27872. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27873. this.mainSoundTrack.switchPanningModelToEqualPower();
  27874. for (var i = 0; i < this.soundTracks.length; i++) {
  27875. this.soundTracks[i].switchPanningModelToEqualPower();
  27876. }
  27877. };
  27878. /**
  27879. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27880. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27881. * @returns the created depth renderer
  27882. */
  27883. Scene.prototype.enableDepthRenderer = function (camera) {
  27884. camera = camera || this.activeCamera;
  27885. if (!camera) {
  27886. throw "No camera available to enable depth renderer";
  27887. }
  27888. if (!this._depthRenderer[camera.id]) {
  27889. var textureType = 0;
  27890. if (this._engine.getCaps().textureHalfFloatRender) {
  27891. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27892. }
  27893. else if (this._engine.getCaps().textureFloatRender) {
  27894. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27895. }
  27896. else {
  27897. throw "Depth renderer does not support int texture type";
  27898. }
  27899. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27900. }
  27901. return this._depthRenderer[camera.id];
  27902. };
  27903. /**
  27904. * Disables a depth renderer for a given camera
  27905. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27906. */
  27907. Scene.prototype.disableDepthRenderer = function (camera) {
  27908. camera = camera || this.activeCamera;
  27909. if (!camera || !this._depthRenderer[camera.id]) {
  27910. return;
  27911. }
  27912. this._depthRenderer[camera.id].dispose();
  27913. delete this._depthRenderer[camera.id];
  27914. };
  27915. /**
  27916. * Enables a GeometryBufferRender and associates it with the scene
  27917. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27918. * @returns the GeometryBufferRenderer
  27919. */
  27920. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27921. if (ratio === void 0) { ratio = 1; }
  27922. if (this._geometryBufferRenderer) {
  27923. return this._geometryBufferRenderer;
  27924. }
  27925. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27926. if (!this._geometryBufferRenderer.isSupported) {
  27927. this._geometryBufferRenderer = null;
  27928. }
  27929. return this._geometryBufferRenderer;
  27930. };
  27931. /**
  27932. * Disables the GeometryBufferRender associated with the scene
  27933. */
  27934. Scene.prototype.disableGeometryBufferRenderer = function () {
  27935. if (!this._geometryBufferRenderer) {
  27936. return;
  27937. }
  27938. this._geometryBufferRenderer.dispose();
  27939. this._geometryBufferRenderer = null;
  27940. };
  27941. /**
  27942. * Freeze all materials
  27943. * A frozen material will not be updatable but should be faster to render
  27944. */
  27945. Scene.prototype.freezeMaterials = function () {
  27946. for (var i = 0; i < this.materials.length; i++) {
  27947. this.materials[i].freeze();
  27948. }
  27949. };
  27950. /**
  27951. * Unfreeze all materials
  27952. * A frozen material will not be updatable but should be faster to render
  27953. */
  27954. Scene.prototype.unfreezeMaterials = function () {
  27955. for (var i = 0; i < this.materials.length; i++) {
  27956. this.materials[i].unfreeze();
  27957. }
  27958. };
  27959. /**
  27960. * Releases all held ressources
  27961. */
  27962. Scene.prototype.dispose = function () {
  27963. this.beforeRender = null;
  27964. this.afterRender = null;
  27965. this.skeletons = [];
  27966. this.morphTargetManagers = [];
  27967. this._transientComponents = [];
  27968. this._isReadyForMeshStage.clear();
  27969. this._beforeEvaluateActiveMeshStage.clear();
  27970. this._evaluateSubMeshStage.clear();
  27971. this._activeMeshStage.clear();
  27972. this._cameraDrawRenderTargetStage.clear();
  27973. this._beforeCameraDrawStage.clear();
  27974. this._beforeRenderingGroupDrawStage.clear();
  27975. this._afterRenderingGroupDrawStage.clear();
  27976. this._afterCameraDrawStage.clear();
  27977. this._beforeCameraUpdateStage.clear();
  27978. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27979. var component = _a[_i];
  27980. component.dispose();
  27981. }
  27982. this.importedMeshesFiles = new Array();
  27983. this.stopAllAnimations();
  27984. this.resetCachedMaterial();
  27985. for (var key in this._depthRenderer) {
  27986. this._depthRenderer[key].dispose();
  27987. }
  27988. // Smart arrays
  27989. if (this.activeCamera) {
  27990. this.activeCamera._activeMeshes.dispose();
  27991. this.activeCamera = null;
  27992. }
  27993. this._activeMeshes.dispose();
  27994. this._renderingManager.dispose();
  27995. this._processedMaterials.dispose();
  27996. this._activeParticleSystems.dispose();
  27997. this._activeSkeletons.dispose();
  27998. this._softwareSkinnedMeshes.dispose();
  27999. this._renderTargets.dispose();
  28000. this._registeredForLateAnimationBindings.dispose();
  28001. this._meshesForIntersections.dispose();
  28002. this._toBeDisposed.dispose();
  28003. // Abort active requests
  28004. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28005. var request = _c[_b];
  28006. request.abort();
  28007. }
  28008. // Debug layer
  28009. if (this._debugLayer) {
  28010. this._debugLayer.hide();
  28011. }
  28012. // Events
  28013. this.onDisposeObservable.notifyObservers(this);
  28014. this.onDisposeObservable.clear();
  28015. this.onBeforeRenderObservable.clear();
  28016. this.onAfterRenderObservable.clear();
  28017. this.onBeforeRenderTargetsRenderObservable.clear();
  28018. this.onAfterRenderTargetsRenderObservable.clear();
  28019. this.onAfterStepObservable.clear();
  28020. this.onBeforeStepObservable.clear();
  28021. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28022. this.onAfterActiveMeshesEvaluationObservable.clear();
  28023. this.onBeforeParticlesRenderingObservable.clear();
  28024. this.onAfterParticlesRenderingObservable.clear();
  28025. this.onBeforeSpritesRenderingObservable.clear();
  28026. this.onAfterSpritesRenderingObservable.clear();
  28027. this.onBeforeDrawPhaseObservable.clear();
  28028. this.onAfterDrawPhaseObservable.clear();
  28029. this.onBeforePhysicsObservable.clear();
  28030. this.onAfterPhysicsObservable.clear();
  28031. this.onBeforeAnimationsObservable.clear();
  28032. this.onAfterAnimationsObservable.clear();
  28033. this.onDataLoadedObservable.clear();
  28034. this.onBeforeRenderingGroupObservable.clear();
  28035. this.onAfterRenderingGroupObservable.clear();
  28036. this.detachControl();
  28037. // Release sounds & sounds tracks
  28038. if (BABYLON.AudioEngine) {
  28039. this.disposeSounds();
  28040. }
  28041. // VR Helper
  28042. if (this.VRHelper) {
  28043. this.VRHelper.dispose();
  28044. }
  28045. // Detach cameras
  28046. var canvas = this._engine.getRenderingCanvas();
  28047. if (canvas) {
  28048. var index;
  28049. for (index = 0; index < this.cameras.length; index++) {
  28050. this.cameras[index].detachControl(canvas);
  28051. }
  28052. }
  28053. // Release animation groups
  28054. while (this.animationGroups.length) {
  28055. this.animationGroups[0].dispose();
  28056. }
  28057. // Release lights
  28058. while (this.lights.length) {
  28059. this.lights[0].dispose();
  28060. }
  28061. // Release meshes
  28062. while (this.meshes.length) {
  28063. this.meshes[0].dispose(true);
  28064. }
  28065. while (this.transformNodes.length) {
  28066. this.removeTransformNode(this.transformNodes[0]);
  28067. }
  28068. // Release cameras
  28069. while (this.cameras.length) {
  28070. this.cameras[0].dispose();
  28071. }
  28072. // Release materials
  28073. if (this.defaultMaterial) {
  28074. this.defaultMaterial.dispose();
  28075. }
  28076. while (this.multiMaterials.length) {
  28077. this.multiMaterials[0].dispose();
  28078. }
  28079. while (this.materials.length) {
  28080. this.materials[0].dispose();
  28081. }
  28082. // Release particles
  28083. while (this.particleSystems.length) {
  28084. this.particleSystems[0].dispose();
  28085. }
  28086. // Release sprites
  28087. while (this.spriteManagers.length) {
  28088. this.spriteManagers[0].dispose();
  28089. }
  28090. // Release postProcesses
  28091. while (this.postProcesses.length) {
  28092. this.postProcesses[0].dispose();
  28093. }
  28094. // Release textures
  28095. while (this.textures.length) {
  28096. this.textures[0].dispose();
  28097. }
  28098. // Release UBO
  28099. this._sceneUbo.dispose();
  28100. if (this._alternateSceneUbo) {
  28101. this._alternateSceneUbo.dispose();
  28102. }
  28103. // Post-processes
  28104. this.postProcessManager.dispose();
  28105. if (this._postProcessRenderPipelineManager) {
  28106. this._postProcessRenderPipelineManager.dispose();
  28107. }
  28108. // Physics
  28109. if (this._physicsEngine) {
  28110. this.disablePhysicsEngine();
  28111. }
  28112. // Remove from engine
  28113. index = this._engine.scenes.indexOf(this);
  28114. if (index > -1) {
  28115. this._engine.scenes.splice(index, 1);
  28116. }
  28117. this._engine.wipeCaches(true);
  28118. this._isDisposed = true;
  28119. };
  28120. Object.defineProperty(Scene.prototype, "isDisposed", {
  28121. /**
  28122. * Gets if the scene is already disposed
  28123. */
  28124. get: function () {
  28125. return this._isDisposed;
  28126. },
  28127. enumerable: true,
  28128. configurable: true
  28129. });
  28130. /**
  28131. * Releases sounds & soundtracks
  28132. */
  28133. Scene.prototype.disposeSounds = function () {
  28134. if (!this._mainSoundTrack) {
  28135. return;
  28136. }
  28137. this.mainSoundTrack.dispose();
  28138. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28139. this.soundTracks[scIndex].dispose();
  28140. }
  28141. };
  28142. /**
  28143. * Call this function to reduce memory footprint of the scene.
  28144. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28145. */
  28146. Scene.prototype.clearCachedVertexData = function () {
  28147. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28148. var mesh = this.meshes[meshIndex];
  28149. var geometry = mesh.geometry;
  28150. if (geometry) {
  28151. geometry._indices = [];
  28152. for (var vbName in geometry._vertexBuffers) {
  28153. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28154. continue;
  28155. }
  28156. geometry._vertexBuffers[vbName]._buffer._data = null;
  28157. }
  28158. }
  28159. }
  28160. };
  28161. /**
  28162. * This function will remove the local cached buffer data from texture.
  28163. * It will save memory but will prevent the texture from being rebuilt
  28164. */
  28165. Scene.prototype.cleanCachedTextureBuffer = function () {
  28166. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28167. var baseTexture = _a[_i];
  28168. var buffer = baseTexture._buffer;
  28169. if (buffer) {
  28170. baseTexture._buffer = null;
  28171. }
  28172. }
  28173. };
  28174. // Octrees
  28175. /**
  28176. * Get the world extend vectors with an optional filter
  28177. *
  28178. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28179. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28180. */
  28181. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28182. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28183. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28184. filterPredicate = filterPredicate || (function () { return true; });
  28185. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28186. mesh.computeWorldMatrix(true);
  28187. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28188. return;
  28189. }
  28190. var boundingInfo = mesh.getBoundingInfo();
  28191. var minBox = boundingInfo.boundingBox.minimumWorld;
  28192. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28193. BABYLON.Tools.CheckExtends(minBox, min, max);
  28194. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28195. });
  28196. return {
  28197. min: min,
  28198. max: max
  28199. };
  28200. };
  28201. /**
  28202. * Creates or updates the octree used to boost selection (picking)
  28203. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28204. * @param maxCapacity defines the maximum capacity per leaf
  28205. * @param maxDepth defines the maximum depth of the octree
  28206. * @returns an octree of AbstractMesh
  28207. */
  28208. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28209. if (maxCapacity === void 0) { maxCapacity = 64; }
  28210. if (maxDepth === void 0) { maxDepth = 2; }
  28211. if (!this._selectionOctree) {
  28212. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28213. }
  28214. var worldExtends = this.getWorldExtends();
  28215. // Update octree
  28216. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28217. return this._selectionOctree;
  28218. };
  28219. // Picking
  28220. /**
  28221. * Creates a ray that can be used to pick in the scene
  28222. * @param x defines the x coordinate of the origin (on-screen)
  28223. * @param y defines the y coordinate of the origin (on-screen)
  28224. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28225. * @param camera defines the camera to use for the picking
  28226. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28227. * @returns a Ray
  28228. */
  28229. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28230. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28231. var result = BABYLON.Ray.Zero();
  28232. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28233. return result;
  28234. };
  28235. /**
  28236. * Creates a ray that can be used to pick in the scene
  28237. * @param x defines the x coordinate of the origin (on-screen)
  28238. * @param y defines the y coordinate of the origin (on-screen)
  28239. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28240. * @param result defines the ray where to store the picking ray
  28241. * @param camera defines the camera to use for the picking
  28242. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28243. * @returns the current scene
  28244. */
  28245. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28246. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28247. var engine = this._engine;
  28248. if (!camera) {
  28249. if (!this.activeCamera)
  28250. throw new Error("Active camera not set");
  28251. camera = this.activeCamera;
  28252. }
  28253. var cameraViewport = camera.viewport;
  28254. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28255. // Moving coordinates to local viewport world
  28256. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28257. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28258. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28259. return this;
  28260. };
  28261. /**
  28262. * Creates a ray that can be used to pick in the scene
  28263. * @param x defines the x coordinate of the origin (on-screen)
  28264. * @param y defines the y coordinate of the origin (on-screen)
  28265. * @param camera defines the camera to use for the picking
  28266. * @returns a Ray
  28267. */
  28268. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28269. var result = BABYLON.Ray.Zero();
  28270. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28271. return result;
  28272. };
  28273. /**
  28274. * Creates a ray that can be used to pick in the scene
  28275. * @param x defines the x coordinate of the origin (on-screen)
  28276. * @param y defines the y coordinate of the origin (on-screen)
  28277. * @param result defines the ray where to store the picking ray
  28278. * @param camera defines the camera to use for the picking
  28279. * @returns the current scene
  28280. */
  28281. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28282. if (!BABYLON.PickingInfo) {
  28283. return this;
  28284. }
  28285. var engine = this._engine;
  28286. if (!camera) {
  28287. if (!this.activeCamera)
  28288. throw new Error("Active camera not set");
  28289. camera = this.activeCamera;
  28290. }
  28291. var cameraViewport = camera.viewport;
  28292. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28293. var identity = BABYLON.Matrix.Identity();
  28294. // Moving coordinates to local viewport world
  28295. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28296. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28297. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28298. return this;
  28299. };
  28300. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28301. if (!BABYLON.PickingInfo) {
  28302. return null;
  28303. }
  28304. var pickingInfo = null;
  28305. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28306. var mesh = this.meshes[meshIndex];
  28307. if (predicate) {
  28308. if (!predicate(mesh)) {
  28309. continue;
  28310. }
  28311. }
  28312. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28313. continue;
  28314. }
  28315. var world = mesh.getWorldMatrix();
  28316. var ray = rayFunction(world);
  28317. var result = mesh.intersects(ray, fastCheck);
  28318. if (!result || !result.hit)
  28319. continue;
  28320. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28321. continue;
  28322. pickingInfo = result;
  28323. if (fastCheck) {
  28324. break;
  28325. }
  28326. }
  28327. return pickingInfo || new BABYLON.PickingInfo();
  28328. };
  28329. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28330. if (!BABYLON.PickingInfo) {
  28331. return null;
  28332. }
  28333. var pickingInfos = new Array();
  28334. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28335. var mesh = this.meshes[meshIndex];
  28336. if (predicate) {
  28337. if (!predicate(mesh)) {
  28338. continue;
  28339. }
  28340. }
  28341. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28342. continue;
  28343. }
  28344. var world = mesh.getWorldMatrix();
  28345. var ray = rayFunction(world);
  28346. var result = mesh.intersects(ray, false);
  28347. if (!result || !result.hit)
  28348. continue;
  28349. pickingInfos.push(result);
  28350. }
  28351. return pickingInfos;
  28352. };
  28353. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28354. if (!BABYLON.PickingInfo) {
  28355. return null;
  28356. }
  28357. var pickingInfo = null;
  28358. if (!camera) {
  28359. if (!this.activeCamera) {
  28360. return null;
  28361. }
  28362. camera = this.activeCamera;
  28363. }
  28364. if (this.spriteManagers.length > 0) {
  28365. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28366. var spriteManager = this.spriteManagers[spriteIndex];
  28367. if (!spriteManager.isPickable) {
  28368. continue;
  28369. }
  28370. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28371. if (!result || !result.hit)
  28372. continue;
  28373. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28374. continue;
  28375. pickingInfo = result;
  28376. if (fastCheck) {
  28377. break;
  28378. }
  28379. }
  28380. }
  28381. return pickingInfo || new BABYLON.PickingInfo();
  28382. };
  28383. /** Launch a ray to try to pick a mesh in the scene
  28384. * @param x position on screen
  28385. * @param y position on screen
  28386. * @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
  28387. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28388. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28389. * @returns a PickingInfo
  28390. */
  28391. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28392. var _this = this;
  28393. if (!BABYLON.PickingInfo) {
  28394. return null;
  28395. }
  28396. var result = this._internalPick(function (world) {
  28397. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28398. return _this._tempPickingRay;
  28399. }, predicate, fastCheck);
  28400. if (result) {
  28401. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28402. }
  28403. return result;
  28404. };
  28405. /** Launch a ray to try to pick a sprite in the scene
  28406. * @param x position on screen
  28407. * @param y position on screen
  28408. * @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
  28409. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28410. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28411. * @returns a PickingInfo
  28412. */
  28413. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28414. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28415. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28416. };
  28417. /** Use the given ray to pick a mesh in the scene
  28418. * @param ray The ray to use to pick meshes
  28419. * @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
  28420. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28421. * @returns a PickingInfo
  28422. */
  28423. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28424. var _this = this;
  28425. var result = this._internalPick(function (world) {
  28426. if (!_this._pickWithRayInverseMatrix) {
  28427. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28428. }
  28429. world.invertToRef(_this._pickWithRayInverseMatrix);
  28430. if (!_this._cachedRayForTransform) {
  28431. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28432. }
  28433. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28434. return _this._cachedRayForTransform;
  28435. }, predicate, fastCheck);
  28436. if (result) {
  28437. result.ray = ray;
  28438. }
  28439. return result;
  28440. };
  28441. /**
  28442. * Launch a ray to try to pick a mesh in the scene
  28443. * @param x X position on screen
  28444. * @param y Y position on screen
  28445. * @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
  28446. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28447. * @returns an array of PickingInfo
  28448. */
  28449. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28450. var _this = this;
  28451. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28452. };
  28453. /**
  28454. * Launch a ray to try to pick a mesh in the scene
  28455. * @param ray Ray to use
  28456. * @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
  28457. * @returns an array of PickingInfo
  28458. */
  28459. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28460. var _this = this;
  28461. return this._internalMultiPick(function (world) {
  28462. if (!_this._pickWithRayInverseMatrix) {
  28463. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28464. }
  28465. world.invertToRef(_this._pickWithRayInverseMatrix);
  28466. if (!_this._cachedRayForTransform) {
  28467. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28468. }
  28469. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28470. return _this._cachedRayForTransform;
  28471. }, predicate);
  28472. };
  28473. /**
  28474. * Force the value of meshUnderPointer
  28475. * @param mesh defines the mesh to use
  28476. */
  28477. Scene.prototype.setPointerOverMesh = function (mesh) {
  28478. if (this._pointerOverMesh === mesh) {
  28479. return;
  28480. }
  28481. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28482. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28483. }
  28484. this._pointerOverMesh = mesh;
  28485. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28486. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28487. }
  28488. };
  28489. /**
  28490. * Gets the mesh under the pointer
  28491. * @returns a Mesh or null if no mesh is under the pointer
  28492. */
  28493. Scene.prototype.getPointerOverMesh = function () {
  28494. return this._pointerOverMesh;
  28495. };
  28496. /**
  28497. * Force the sprite under the pointer
  28498. * @param sprite defines the sprite to use
  28499. */
  28500. Scene.prototype.setPointerOverSprite = function (sprite) {
  28501. if (this._pointerOverSprite === sprite) {
  28502. return;
  28503. }
  28504. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28505. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28506. }
  28507. this._pointerOverSprite = sprite;
  28508. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28509. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28510. }
  28511. };
  28512. /**
  28513. * Gets the sprite under the pointer
  28514. * @returns a Sprite or null if no sprite is under the pointer
  28515. */
  28516. Scene.prototype.getPointerOverSprite = function () {
  28517. return this._pointerOverSprite;
  28518. };
  28519. // Physics
  28520. /**
  28521. * Gets the current physics engine
  28522. * @returns a PhysicsEngine or null if none attached
  28523. */
  28524. Scene.prototype.getPhysicsEngine = function () {
  28525. return this._physicsEngine;
  28526. };
  28527. /**
  28528. * Enables physics to the current scene
  28529. * @param gravity defines the scene's gravity for the physics engine
  28530. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28531. * @return a boolean indicating if the physics engine was initialized
  28532. */
  28533. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28534. if (gravity === void 0) { gravity = null; }
  28535. if (this._physicsEngine) {
  28536. return true;
  28537. }
  28538. try {
  28539. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28540. return true;
  28541. }
  28542. catch (e) {
  28543. BABYLON.Tools.Error(e.message);
  28544. return false;
  28545. }
  28546. };
  28547. /**
  28548. * Disables and disposes the physics engine associated with the scene
  28549. */
  28550. Scene.prototype.disablePhysicsEngine = function () {
  28551. if (!this._physicsEngine) {
  28552. return;
  28553. }
  28554. this._physicsEngine.dispose();
  28555. this._physicsEngine = null;
  28556. };
  28557. /**
  28558. * Gets a boolean indicating if there is an active physics engine
  28559. * @returns a boolean indicating if there is an active physics engine
  28560. */
  28561. Scene.prototype.isPhysicsEnabled = function () {
  28562. return this._physicsEngine !== undefined;
  28563. };
  28564. /**
  28565. * Deletes a physics compound impostor
  28566. * @param compound defines the compound to delete
  28567. */
  28568. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28569. var mesh = compound.parts[0].mesh;
  28570. if (mesh.physicsImpostor) {
  28571. mesh.physicsImpostor.dispose( /*true*/);
  28572. mesh.physicsImpostor = null;
  28573. }
  28574. };
  28575. // Misc.
  28576. /** @hidden */
  28577. Scene.prototype._rebuildGeometries = function () {
  28578. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28579. var geometry = _a[_i];
  28580. geometry._rebuild();
  28581. }
  28582. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28583. var mesh = _c[_b];
  28584. mesh._rebuild();
  28585. }
  28586. if (this.postProcessManager) {
  28587. this.postProcessManager._rebuild();
  28588. }
  28589. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28590. var component = _e[_d];
  28591. component.rebuild();
  28592. }
  28593. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28594. var system = _g[_f];
  28595. system.rebuild();
  28596. }
  28597. if (this._postProcessRenderPipelineManager) {
  28598. this._postProcessRenderPipelineManager._rebuild();
  28599. }
  28600. };
  28601. /** @hidden */
  28602. Scene.prototype._rebuildTextures = function () {
  28603. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28604. var texture = _a[_i];
  28605. texture._rebuild();
  28606. }
  28607. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28608. };
  28609. /**
  28610. * Creates a default light for the scene.
  28611. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28612. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28613. */
  28614. Scene.prototype.createDefaultLight = function (replace) {
  28615. if (replace === void 0) { replace = false; }
  28616. // Dispose existing light in replace mode.
  28617. if (replace) {
  28618. if (this.lights) {
  28619. for (var i = 0; i < this.lights.length; i++) {
  28620. this.lights[i].dispose();
  28621. }
  28622. }
  28623. }
  28624. // Light
  28625. if (this.lights.length === 0) {
  28626. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28627. }
  28628. };
  28629. /**
  28630. * Creates a default camera for the scene.
  28631. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28632. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28633. * @param replace has default false, when true replaces the active camera in the scene
  28634. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28635. */
  28636. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28637. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28638. if (replace === void 0) { replace = false; }
  28639. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28640. // Dispose existing camera in replace mode.
  28641. if (replace) {
  28642. if (this.activeCamera) {
  28643. this.activeCamera.dispose();
  28644. this.activeCamera = null;
  28645. }
  28646. }
  28647. // Camera
  28648. if (!this.activeCamera) {
  28649. var worldExtends = this.getWorldExtends();
  28650. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28651. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28652. var camera;
  28653. var radius = worldSize.length() * 1.5;
  28654. // empty scene scenario!
  28655. if (!isFinite(radius)) {
  28656. radius = 1;
  28657. worldCenter.copyFromFloats(0, 0, 0);
  28658. }
  28659. if (createArcRotateCamera) {
  28660. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28661. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28662. arcRotateCamera.wheelPrecision = 100 / radius;
  28663. camera = arcRotateCamera;
  28664. }
  28665. else {
  28666. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28667. freeCamera.setTarget(worldCenter);
  28668. camera = freeCamera;
  28669. }
  28670. camera.minZ = radius * 0.01;
  28671. camera.maxZ = radius * 1000;
  28672. camera.speed = radius * 0.2;
  28673. this.activeCamera = camera;
  28674. var canvas = this.getEngine().getRenderingCanvas();
  28675. if (attachCameraControls && canvas) {
  28676. camera.attachControl(canvas);
  28677. }
  28678. }
  28679. };
  28680. /**
  28681. * Creates a default camera and a default light.
  28682. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28683. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28684. * @param replace has the default false, when true replaces the active camera/light in the scene
  28685. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28686. */
  28687. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28688. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28689. if (replace === void 0) { replace = false; }
  28690. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28691. this.createDefaultLight(replace);
  28692. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28693. };
  28694. /**
  28695. * Creates a new sky box
  28696. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28697. * @param environmentTexture defines the texture to use as environment texture
  28698. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28699. * @param scale defines the overall scale of the skybox
  28700. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28701. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28702. * @returns a new mesh holding the sky box
  28703. */
  28704. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28705. if (pbr === void 0) { pbr = false; }
  28706. if (scale === void 0) { scale = 1000; }
  28707. if (blur === void 0) { blur = 0; }
  28708. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28709. if (!environmentTexture) {
  28710. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28711. return null;
  28712. }
  28713. if (setGlobalEnvTexture) {
  28714. if (environmentTexture) {
  28715. this.environmentTexture = environmentTexture;
  28716. }
  28717. }
  28718. // Skybox
  28719. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28720. if (pbr) {
  28721. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28722. hdrSkyboxMaterial.backFaceCulling = false;
  28723. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28724. if (hdrSkyboxMaterial.reflectionTexture) {
  28725. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28726. }
  28727. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28728. hdrSkyboxMaterial.disableLighting = true;
  28729. hdrSkyboxMaterial.twoSidedLighting = true;
  28730. hdrSkybox.infiniteDistance = true;
  28731. hdrSkybox.material = hdrSkyboxMaterial;
  28732. }
  28733. else {
  28734. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28735. skyboxMaterial.backFaceCulling = false;
  28736. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28737. if (skyboxMaterial.reflectionTexture) {
  28738. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28739. }
  28740. skyboxMaterial.disableLighting = true;
  28741. hdrSkybox.infiniteDistance = true;
  28742. hdrSkybox.material = skyboxMaterial;
  28743. }
  28744. return hdrSkybox;
  28745. };
  28746. /**
  28747. * Creates a new environment
  28748. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28749. * @param options defines the options you can use to configure the environment
  28750. * @returns the new EnvironmentHelper
  28751. */
  28752. Scene.prototype.createDefaultEnvironment = function (options) {
  28753. if (BABYLON.EnvironmentHelper) {
  28754. return new BABYLON.EnvironmentHelper(options, this);
  28755. }
  28756. return null;
  28757. };
  28758. /**
  28759. * Creates a new VREXperienceHelper
  28760. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28761. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28762. * @returns a new VREXperienceHelper
  28763. */
  28764. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28765. if (webVROptions === void 0) { webVROptions = {}; }
  28766. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28767. };
  28768. // Tags
  28769. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28770. if (tagsQuery === undefined) {
  28771. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28772. return list;
  28773. }
  28774. var listByTags = [];
  28775. forEach = forEach || (function (item) { return; });
  28776. for (var i in list) {
  28777. var item = list[i];
  28778. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28779. listByTags.push(item);
  28780. forEach(item);
  28781. }
  28782. }
  28783. return listByTags;
  28784. };
  28785. /**
  28786. * Get a list of meshes by tags
  28787. * @param tagsQuery defines the tags query to use
  28788. * @param forEach defines a predicate used to filter results
  28789. * @returns an array of Mesh
  28790. */
  28791. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28792. return this._getByTags(this.meshes, tagsQuery, forEach);
  28793. };
  28794. /**
  28795. * Get a list of cameras by tags
  28796. * @param tagsQuery defines the tags query to use
  28797. * @param forEach defines a predicate used to filter results
  28798. * @returns an array of Camera
  28799. */
  28800. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28801. return this._getByTags(this.cameras, tagsQuery, forEach);
  28802. };
  28803. /**
  28804. * Get a list of lights by tags
  28805. * @param tagsQuery defines the tags query to use
  28806. * @param forEach defines a predicate used to filter results
  28807. * @returns an array of Light
  28808. */
  28809. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28810. return this._getByTags(this.lights, tagsQuery, forEach);
  28811. };
  28812. /**
  28813. * Get a list of materials by tags
  28814. * @param tagsQuery defines the tags query to use
  28815. * @param forEach defines a predicate used to filter results
  28816. * @returns an array of Material
  28817. */
  28818. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28819. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28820. };
  28821. /**
  28822. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28823. * This allowed control for front to back rendering or reversly depending of the special needs.
  28824. *
  28825. * @param renderingGroupId The rendering group id corresponding to its index
  28826. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28827. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28828. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28829. */
  28830. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28831. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28832. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28833. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28834. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28835. };
  28836. /**
  28837. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28838. *
  28839. * @param renderingGroupId The rendering group id corresponding to its index
  28840. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28841. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28842. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28843. */
  28844. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28845. if (depth === void 0) { depth = true; }
  28846. if (stencil === void 0) { stencil = true; }
  28847. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28848. };
  28849. /**
  28850. * Gets the current auto clear configuration for one rendering group of the rendering
  28851. * manager.
  28852. * @param index the rendering group index to get the information for
  28853. * @returns The auto clear setup for the requested rendering group
  28854. */
  28855. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28856. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28857. };
  28858. /**
  28859. * Will flag all materials as dirty to trigger new shader compilation
  28860. * @param flag defines the flag used to specify which material part must be marked as dirty
  28861. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28862. */
  28863. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28864. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28865. var material = _a[_i];
  28866. if (predicate && !predicate(material)) {
  28867. continue;
  28868. }
  28869. material.markAsDirty(flag);
  28870. }
  28871. };
  28872. /** @hidden */
  28873. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28874. var _this = this;
  28875. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28876. this._activeRequests.push(request);
  28877. request.onCompleteObservable.add(function (request) {
  28878. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28879. });
  28880. return request;
  28881. };
  28882. /** @hidden */
  28883. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28884. var _this = this;
  28885. return new Promise(function (resolve, reject) {
  28886. _this._loadFile(url, function (data) {
  28887. resolve(data);
  28888. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28889. reject(exception);
  28890. });
  28891. });
  28892. };
  28893. // Statics
  28894. Scene._FOGMODE_NONE = 0;
  28895. Scene._FOGMODE_EXP = 1;
  28896. Scene._FOGMODE_EXP2 = 2;
  28897. Scene._FOGMODE_LINEAR = 3;
  28898. Scene._uniqueIdCounter = 0;
  28899. /**
  28900. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28901. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28902. */
  28903. Scene.MinDeltaTime = 1.0;
  28904. /**
  28905. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28906. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28907. */
  28908. Scene.MaxDeltaTime = 1000.0;
  28909. /** The distance in pixel that you have to move to prevent some events */
  28910. Scene.DragMovementThreshold = 10; // in pixels
  28911. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28912. Scene.LongPressDelay = 500; // in milliseconds
  28913. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28914. Scene.DoubleClickDelay = 300; // in milliseconds
  28915. /** If you need to check double click without raising a single click at first click, enable this flag */
  28916. Scene.ExclusiveDoubleClickMode = false;
  28917. return Scene;
  28918. }(BABYLON.AbstractScene));
  28919. BABYLON.Scene = Scene;
  28920. })(BABYLON || (BABYLON = {}));
  28921. //# sourceMappingURL=babylon.scene.js.map
  28922. var BABYLON;
  28923. (function (BABYLON) {
  28924. /**
  28925. * Set of assets to keep when moving a scene into an asset container.
  28926. */
  28927. var KeepAssets = /** @class */ (function (_super) {
  28928. __extends(KeepAssets, _super);
  28929. function KeepAssets() {
  28930. return _super !== null && _super.apply(this, arguments) || this;
  28931. }
  28932. return KeepAssets;
  28933. }(BABYLON.AbstractScene));
  28934. BABYLON.KeepAssets = KeepAssets;
  28935. /**
  28936. * Container with a set of assets that can be added or removed from a scene.
  28937. */
  28938. var AssetContainer = /** @class */ (function (_super) {
  28939. __extends(AssetContainer, _super);
  28940. /**
  28941. * Instantiates an AssetContainer.
  28942. * @param scene The scene the AssetContainer belongs to.
  28943. */
  28944. function AssetContainer(scene) {
  28945. var _this = _super.call(this) || this;
  28946. _this.scene = scene;
  28947. return _this;
  28948. }
  28949. /**
  28950. * Adds all the assets from the container to the scene.
  28951. */
  28952. AssetContainer.prototype.addAllToScene = function () {
  28953. var _this = this;
  28954. this.cameras.forEach(function (o) {
  28955. _this.scene.addCamera(o);
  28956. });
  28957. this.lights.forEach(function (o) {
  28958. _this.scene.addLight(o);
  28959. });
  28960. this.meshes.forEach(function (o) {
  28961. _this.scene.addMesh(o);
  28962. });
  28963. this.skeletons.forEach(function (o) {
  28964. _this.scene.addSkeleton(o);
  28965. });
  28966. this.animations.forEach(function (o) {
  28967. _this.scene.addAnimation(o);
  28968. });
  28969. this.animationGroups.forEach(function (o) {
  28970. _this.scene.addAnimationGroup(o);
  28971. });
  28972. this.multiMaterials.forEach(function (o) {
  28973. _this.scene.addMultiMaterial(o);
  28974. });
  28975. this.materials.forEach(function (o) {
  28976. _this.scene.addMaterial(o);
  28977. });
  28978. this.morphTargetManagers.forEach(function (o) {
  28979. _this.scene.addMorphTargetManager(o);
  28980. });
  28981. this.geometries.forEach(function (o) {
  28982. _this.scene.addGeometry(o);
  28983. });
  28984. this.transformNodes.forEach(function (o) {
  28985. _this.scene.addTransformNode(o);
  28986. });
  28987. this.actionManagers.forEach(function (o) {
  28988. _this.scene.addActionManager(o);
  28989. });
  28990. this.sounds.forEach(function (o) {
  28991. o.play();
  28992. o.autoplay = true;
  28993. _this.scene.mainSoundTrack.AddSound(o);
  28994. });
  28995. this.textures.forEach(function (o) {
  28996. _this.scene.addTexture(o);
  28997. });
  28998. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28999. var component = _a[_i];
  29000. component.addFromContainer(this.scene);
  29001. }
  29002. };
  29003. /**
  29004. * Removes all the assets in the container from the scene
  29005. */
  29006. AssetContainer.prototype.removeAllFromScene = function () {
  29007. var _this = this;
  29008. this.cameras.forEach(function (o) {
  29009. _this.scene.removeCamera(o);
  29010. });
  29011. this.lights.forEach(function (o) {
  29012. _this.scene.removeLight(o);
  29013. });
  29014. this.meshes.forEach(function (o) {
  29015. _this.scene.removeMesh(o);
  29016. });
  29017. this.skeletons.forEach(function (o) {
  29018. _this.scene.removeSkeleton(o);
  29019. });
  29020. this.animations.forEach(function (o) {
  29021. _this.scene.removeAnimation(o);
  29022. });
  29023. this.animationGroups.forEach(function (o) {
  29024. _this.scene.removeAnimationGroup(o);
  29025. });
  29026. this.multiMaterials.forEach(function (o) {
  29027. _this.scene.removeMultiMaterial(o);
  29028. });
  29029. this.materials.forEach(function (o) {
  29030. _this.scene.removeMaterial(o);
  29031. });
  29032. this.morphTargetManagers.forEach(function (o) {
  29033. _this.scene.removeMorphTargetManager(o);
  29034. });
  29035. this.geometries.forEach(function (o) {
  29036. _this.scene.removeGeometry(o);
  29037. });
  29038. this.transformNodes.forEach(function (o) {
  29039. _this.scene.removeTransformNode(o);
  29040. });
  29041. this.actionManagers.forEach(function (o) {
  29042. _this.scene.removeActionManager(o);
  29043. });
  29044. this.sounds.forEach(function (o) {
  29045. o.stop();
  29046. o.autoplay = false;
  29047. _this.scene.mainSoundTrack.RemoveSound(o);
  29048. });
  29049. this.textures.forEach(function (o) {
  29050. _this.scene.removeTexture(o);
  29051. });
  29052. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29053. var component = _a[_i];
  29054. component.removeFromContainer(this.scene);
  29055. }
  29056. };
  29057. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29058. if (!sourceAssets) {
  29059. return;
  29060. }
  29061. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29062. var asset = sourceAssets_1[_i];
  29063. var move = true;
  29064. if (keepAssets) {
  29065. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29066. var keepAsset = keepAssets_1[_a];
  29067. if (asset === keepAsset) {
  29068. move = false;
  29069. break;
  29070. }
  29071. }
  29072. }
  29073. if (move) {
  29074. targetAssets.push(asset);
  29075. }
  29076. }
  29077. };
  29078. /**
  29079. * Removes all the assets contained in the scene and adds them to the container.
  29080. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29081. */
  29082. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29083. if (keepAssets === undefined) {
  29084. keepAssets = new KeepAssets();
  29085. }
  29086. for (var key in this) {
  29087. if (this.hasOwnProperty(key)) {
  29088. this[key] = this[key] || [];
  29089. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29090. }
  29091. }
  29092. this.removeAllFromScene();
  29093. };
  29094. /**
  29095. * 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.
  29096. * @returns the root mesh
  29097. */
  29098. AssetContainer.prototype.createRootMesh = function () {
  29099. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29100. this.meshes.forEach(function (m) {
  29101. if (!m.parent) {
  29102. rootMesh.addChild(m);
  29103. }
  29104. });
  29105. this.meshes.unshift(rootMesh);
  29106. return rootMesh;
  29107. };
  29108. return AssetContainer;
  29109. }(BABYLON.AbstractScene));
  29110. BABYLON.AssetContainer = AssetContainer;
  29111. })(BABYLON || (BABYLON = {}));
  29112. //# sourceMappingURL=babylon.assetContainer.js.map
  29113. var BABYLON;
  29114. (function (BABYLON) {
  29115. var Buffer = /** @class */ (function () {
  29116. /**
  29117. * Constructor
  29118. * @param engine the engine
  29119. * @param data the data to use for this buffer
  29120. * @param updatable whether the data is updatable
  29121. * @param stride the stride (optional)
  29122. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29123. * @param instanced whether the buffer is instanced (optional)
  29124. * @param useBytes set to true if the stride in in bytes (optional)
  29125. */
  29126. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29127. if (stride === void 0) { stride = 0; }
  29128. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29129. if (instanced === void 0) { instanced = false; }
  29130. if (useBytes === void 0) { useBytes = false; }
  29131. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29132. this._engine = engine.getScene().getEngine();
  29133. }
  29134. else {
  29135. this._engine = engine;
  29136. }
  29137. this._updatable = updatable;
  29138. this._instanced = instanced;
  29139. this._data = data;
  29140. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29141. if (!postponeInternalCreation) { // by default
  29142. this.create();
  29143. }
  29144. }
  29145. /**
  29146. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29147. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29148. * @param offset defines offset in the buffer (0 by default)
  29149. * @param size defines the size in floats of attributes (position is 3 for instance)
  29150. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29151. * @param instanced defines if the vertex buffer contains indexed data
  29152. * @param useBytes defines if the offset and stride are in bytes
  29153. * @returns the new vertex buffer
  29154. */
  29155. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29156. if (useBytes === void 0) { useBytes = false; }
  29157. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29158. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29159. // a lot of these parameters are ignored as they are overriden by the buffer
  29160. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29161. };
  29162. // Properties
  29163. Buffer.prototype.isUpdatable = function () {
  29164. return this._updatable;
  29165. };
  29166. Buffer.prototype.getData = function () {
  29167. return this._data;
  29168. };
  29169. Buffer.prototype.getBuffer = function () {
  29170. return this._buffer;
  29171. };
  29172. /**
  29173. * Gets the stride in float32 units (i.e. byte stride / 4).
  29174. * May not be an integer if the byte stride is not divisible by 4.
  29175. * DEPRECATED. Use byteStride instead.
  29176. * @returns the stride in float32 units
  29177. */
  29178. Buffer.prototype.getStrideSize = function () {
  29179. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29180. };
  29181. // Methods
  29182. Buffer.prototype.create = function (data) {
  29183. if (data === void 0) { data = null; }
  29184. if (!data && this._buffer) {
  29185. return; // nothing to do
  29186. }
  29187. data = data || this._data;
  29188. if (!data) {
  29189. return;
  29190. }
  29191. if (!this._buffer) { // create buffer
  29192. if (this._updatable) {
  29193. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29194. this._data = data;
  29195. }
  29196. else {
  29197. this._buffer = this._engine.createVertexBuffer(data);
  29198. }
  29199. }
  29200. else if (this._updatable) { // update buffer
  29201. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29202. this._data = data;
  29203. }
  29204. };
  29205. /** @hidden */
  29206. Buffer.prototype._rebuild = function () {
  29207. this._buffer = null;
  29208. this.create(this._data);
  29209. };
  29210. Buffer.prototype.update = function (data) {
  29211. this.create(data);
  29212. };
  29213. /**
  29214. * Updates the data directly.
  29215. * @param data the new data
  29216. * @param offset the new offset
  29217. * @param vertexCount the vertex count (optional)
  29218. * @param useBytes set to true if the offset is in bytes
  29219. */
  29220. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29221. if (useBytes === void 0) { useBytes = false; }
  29222. if (!this._buffer) {
  29223. return;
  29224. }
  29225. if (this._updatable) { // update buffer
  29226. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29227. this._data = null;
  29228. }
  29229. };
  29230. Buffer.prototype.dispose = function () {
  29231. if (!this._buffer) {
  29232. return;
  29233. }
  29234. if (this._engine._releaseBuffer(this._buffer)) {
  29235. this._buffer = null;
  29236. }
  29237. };
  29238. return Buffer;
  29239. }());
  29240. BABYLON.Buffer = Buffer;
  29241. })(BABYLON || (BABYLON = {}));
  29242. //# sourceMappingURL=babylon.buffer.js.map
  29243. var BABYLON;
  29244. (function (BABYLON) {
  29245. var VertexBuffer = /** @class */ (function () {
  29246. /**
  29247. * Constructor
  29248. * @param engine the engine
  29249. * @param data the data to use for this vertex buffer
  29250. * @param kind the vertex buffer kind
  29251. * @param updatable whether the data is updatable
  29252. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29253. * @param stride the stride (optional)
  29254. * @param instanced whether the buffer is instanced (optional)
  29255. * @param offset the offset of the data (optional)
  29256. * @param size the number of components (optional)
  29257. * @param type the type of the component (optional)
  29258. * @param normalized whether the data contains normalized data (optional)
  29259. * @param useBytes set to true if stride and offset are in bytes (optional)
  29260. */
  29261. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29262. if (normalized === void 0) { normalized = false; }
  29263. if (useBytes === void 0) { useBytes = false; }
  29264. if (data instanceof BABYLON.Buffer) {
  29265. this._buffer = data;
  29266. this._ownsBuffer = false;
  29267. }
  29268. else {
  29269. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29270. this._ownsBuffer = true;
  29271. }
  29272. this._kind = kind;
  29273. if (type == undefined) {
  29274. var data_1 = this.getData();
  29275. this.type = VertexBuffer.FLOAT;
  29276. if (data_1 instanceof Int8Array)
  29277. this.type = VertexBuffer.BYTE;
  29278. else if (data_1 instanceof Uint8Array)
  29279. this.type = VertexBuffer.UNSIGNED_BYTE;
  29280. else if (data_1 instanceof Int16Array)
  29281. this.type = VertexBuffer.SHORT;
  29282. else if (data_1 instanceof Uint16Array)
  29283. this.type = VertexBuffer.UNSIGNED_SHORT;
  29284. else if (data_1 instanceof Int32Array)
  29285. this.type = VertexBuffer.INT;
  29286. else if (data_1 instanceof Uint32Array)
  29287. this.type = VertexBuffer.UNSIGNED_INT;
  29288. }
  29289. else {
  29290. this.type = type;
  29291. }
  29292. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29293. if (useBytes) {
  29294. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29295. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29296. this.byteOffset = offset || 0;
  29297. }
  29298. else {
  29299. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29300. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29301. this.byteOffset = (offset || 0) * typeByteLength;
  29302. }
  29303. this.normalized = normalized;
  29304. this._instanced = instanced !== undefined ? instanced : false;
  29305. this._instanceDivisor = instanced ? 1 : 0;
  29306. }
  29307. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29308. /**
  29309. * Gets or sets the instance divisor when in instanced mode
  29310. */
  29311. get: function () {
  29312. return this._instanceDivisor;
  29313. },
  29314. set: function (value) {
  29315. this._instanceDivisor = value;
  29316. if (value == 0) {
  29317. this._instanced = false;
  29318. }
  29319. else {
  29320. this._instanced = true;
  29321. }
  29322. },
  29323. enumerable: true,
  29324. configurable: true
  29325. });
  29326. /** @hidden */
  29327. VertexBuffer.prototype._rebuild = function () {
  29328. if (!this._buffer) {
  29329. return;
  29330. }
  29331. this._buffer._rebuild();
  29332. };
  29333. /**
  29334. * Returns the kind of the VertexBuffer (string).
  29335. */
  29336. VertexBuffer.prototype.getKind = function () {
  29337. return this._kind;
  29338. };
  29339. // Properties
  29340. /**
  29341. * Boolean : is the VertexBuffer updatable ?
  29342. */
  29343. VertexBuffer.prototype.isUpdatable = function () {
  29344. return this._buffer.isUpdatable();
  29345. };
  29346. /**
  29347. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29348. */
  29349. VertexBuffer.prototype.getData = function () {
  29350. return this._buffer.getData();
  29351. };
  29352. /**
  29353. * Returns the WebGLBuffer associated to the VertexBuffer.
  29354. */
  29355. VertexBuffer.prototype.getBuffer = function () {
  29356. return this._buffer.getBuffer();
  29357. };
  29358. /**
  29359. * Returns the stride as a multiple of the type byte length.
  29360. * DEPRECATED. Use byteStride instead.
  29361. */
  29362. VertexBuffer.prototype.getStrideSize = function () {
  29363. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29364. };
  29365. /**
  29366. * Returns the offset as a multiple of the type byte length.
  29367. * DEPRECATED. Use byteOffset instead.
  29368. */
  29369. VertexBuffer.prototype.getOffset = function () {
  29370. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29371. };
  29372. /**
  29373. * Returns the number of components per vertex attribute (integer).
  29374. */
  29375. VertexBuffer.prototype.getSize = function () {
  29376. return this._size;
  29377. };
  29378. /**
  29379. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29380. */
  29381. VertexBuffer.prototype.getIsInstanced = function () {
  29382. return this._instanced;
  29383. };
  29384. /**
  29385. * Returns the instancing divisor, zero for non-instanced (integer).
  29386. */
  29387. VertexBuffer.prototype.getInstanceDivisor = function () {
  29388. return this._instanceDivisor;
  29389. };
  29390. // Methods
  29391. /**
  29392. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29393. * Returns the created WebGLBuffer.
  29394. */
  29395. VertexBuffer.prototype.create = function (data) {
  29396. return this._buffer.create(data);
  29397. };
  29398. /**
  29399. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29400. * This function will create a new buffer if the current one is not updatable
  29401. * Returns the updated WebGLBuffer.
  29402. */
  29403. VertexBuffer.prototype.update = function (data) {
  29404. return this._buffer.update(data);
  29405. };
  29406. /**
  29407. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29408. * Returns the directly updated WebGLBuffer.
  29409. * @param data the new data
  29410. * @param offset the new offset
  29411. * @param useBytes set to true if the offset is in bytes
  29412. */
  29413. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29414. if (useBytes === void 0) { useBytes = false; }
  29415. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29416. };
  29417. /**
  29418. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29419. */
  29420. VertexBuffer.prototype.dispose = function () {
  29421. if (this._ownsBuffer) {
  29422. this._buffer.dispose();
  29423. }
  29424. };
  29425. /**
  29426. * Enumerates each value of this vertex buffer as numbers.
  29427. * @param count the number of values to enumerate
  29428. * @param callback the callback function called for each value
  29429. */
  29430. VertexBuffer.prototype.forEach = function (count, callback) {
  29431. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29432. };
  29433. Object.defineProperty(VertexBuffer, "PositionKind", {
  29434. get: function () {
  29435. return VertexBuffer._PositionKind;
  29436. },
  29437. enumerable: true,
  29438. configurable: true
  29439. });
  29440. Object.defineProperty(VertexBuffer, "NormalKind", {
  29441. get: function () {
  29442. return VertexBuffer._NormalKind;
  29443. },
  29444. enumerable: true,
  29445. configurable: true
  29446. });
  29447. Object.defineProperty(VertexBuffer, "TangentKind", {
  29448. get: function () {
  29449. return VertexBuffer._TangentKind;
  29450. },
  29451. enumerable: true,
  29452. configurable: true
  29453. });
  29454. Object.defineProperty(VertexBuffer, "UVKind", {
  29455. get: function () {
  29456. return VertexBuffer._UVKind;
  29457. },
  29458. enumerable: true,
  29459. configurable: true
  29460. });
  29461. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29462. get: function () {
  29463. return VertexBuffer._UV2Kind;
  29464. },
  29465. enumerable: true,
  29466. configurable: true
  29467. });
  29468. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29469. get: function () {
  29470. return VertexBuffer._UV3Kind;
  29471. },
  29472. enumerable: true,
  29473. configurable: true
  29474. });
  29475. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29476. get: function () {
  29477. return VertexBuffer._UV4Kind;
  29478. },
  29479. enumerable: true,
  29480. configurable: true
  29481. });
  29482. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29483. get: function () {
  29484. return VertexBuffer._UV5Kind;
  29485. },
  29486. enumerable: true,
  29487. configurable: true
  29488. });
  29489. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29490. get: function () {
  29491. return VertexBuffer._UV6Kind;
  29492. },
  29493. enumerable: true,
  29494. configurable: true
  29495. });
  29496. Object.defineProperty(VertexBuffer, "ColorKind", {
  29497. get: function () {
  29498. return VertexBuffer._ColorKind;
  29499. },
  29500. enumerable: true,
  29501. configurable: true
  29502. });
  29503. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29504. get: function () {
  29505. return VertexBuffer._MatricesIndicesKind;
  29506. },
  29507. enumerable: true,
  29508. configurable: true
  29509. });
  29510. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29511. get: function () {
  29512. return VertexBuffer._MatricesWeightsKind;
  29513. },
  29514. enumerable: true,
  29515. configurable: true
  29516. });
  29517. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29518. get: function () {
  29519. return VertexBuffer._MatricesIndicesExtraKind;
  29520. },
  29521. enumerable: true,
  29522. configurable: true
  29523. });
  29524. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29525. get: function () {
  29526. return VertexBuffer._MatricesWeightsExtraKind;
  29527. },
  29528. enumerable: true,
  29529. configurable: true
  29530. });
  29531. /**
  29532. * Deduces the stride given a kind.
  29533. * @param kind The kind string to deduce
  29534. * @returns The deduced stride
  29535. */
  29536. VertexBuffer.DeduceStride = function (kind) {
  29537. switch (kind) {
  29538. case VertexBuffer.UVKind:
  29539. case VertexBuffer.UV2Kind:
  29540. case VertexBuffer.UV3Kind:
  29541. case VertexBuffer.UV4Kind:
  29542. case VertexBuffer.UV5Kind:
  29543. case VertexBuffer.UV6Kind:
  29544. return 2;
  29545. case VertexBuffer.NormalKind:
  29546. case VertexBuffer.PositionKind:
  29547. return 3;
  29548. case VertexBuffer.ColorKind:
  29549. case VertexBuffer.MatricesIndicesKind:
  29550. case VertexBuffer.MatricesIndicesExtraKind:
  29551. case VertexBuffer.MatricesWeightsKind:
  29552. case VertexBuffer.MatricesWeightsExtraKind:
  29553. case VertexBuffer.TangentKind:
  29554. return 4;
  29555. default:
  29556. throw new Error("Invalid kind '" + kind + "'");
  29557. }
  29558. };
  29559. /**
  29560. * Gets the byte length of the given type.
  29561. * @param type the type
  29562. * @returns the number of bytes
  29563. */
  29564. VertexBuffer.GetTypeByteLength = function (type) {
  29565. switch (type) {
  29566. case VertexBuffer.BYTE:
  29567. case VertexBuffer.UNSIGNED_BYTE:
  29568. return 1;
  29569. case VertexBuffer.SHORT:
  29570. case VertexBuffer.UNSIGNED_SHORT:
  29571. return 2;
  29572. case VertexBuffer.INT:
  29573. case VertexBuffer.FLOAT:
  29574. return 4;
  29575. default:
  29576. throw new Error("Invalid type '" + type + "'");
  29577. }
  29578. };
  29579. /**
  29580. * Enumerates each value of the given parameters as numbers.
  29581. * @param data the data to enumerate
  29582. * @param byteOffset the byte offset of the data
  29583. * @param byteStride the byte stride of the data
  29584. * @param componentCount the number of components per element
  29585. * @param componentType the type of the component
  29586. * @param count the total number of components
  29587. * @param normalized whether the data is normalized
  29588. * @param callback the callback function called for each value
  29589. */
  29590. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29591. if (data instanceof Array) {
  29592. var offset = byteOffset / 4;
  29593. var stride = byteStride / 4;
  29594. for (var index = 0; index < count; index += componentCount) {
  29595. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29596. callback(data[offset + componentIndex], index + componentIndex);
  29597. }
  29598. offset += stride;
  29599. }
  29600. }
  29601. else {
  29602. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29603. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29604. for (var index = 0; index < count; index += componentCount) {
  29605. var componentByteOffset = byteOffset;
  29606. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29607. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29608. callback(value, index + componentIndex);
  29609. componentByteOffset += componentByteLength;
  29610. }
  29611. byteOffset += byteStride;
  29612. }
  29613. }
  29614. };
  29615. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29616. switch (type) {
  29617. case VertexBuffer.BYTE: {
  29618. var value = dataView.getInt8(byteOffset);
  29619. if (normalized) {
  29620. value = Math.max(value / 127, -1);
  29621. }
  29622. return value;
  29623. }
  29624. case VertexBuffer.UNSIGNED_BYTE: {
  29625. var value = dataView.getUint8(byteOffset);
  29626. if (normalized) {
  29627. value = value / 255;
  29628. }
  29629. return value;
  29630. }
  29631. case VertexBuffer.SHORT: {
  29632. var value = dataView.getInt16(byteOffset, true);
  29633. if (normalized) {
  29634. value = Math.max(value / 16383, -1);
  29635. }
  29636. return value;
  29637. }
  29638. case VertexBuffer.UNSIGNED_SHORT: {
  29639. var value = dataView.getUint16(byteOffset, true);
  29640. if (normalized) {
  29641. value = value / 65535;
  29642. }
  29643. return value;
  29644. }
  29645. case VertexBuffer.FLOAT: {
  29646. return dataView.getFloat32(byteOffset, true);
  29647. }
  29648. default: {
  29649. throw new Error("Invalid component type " + type);
  29650. }
  29651. }
  29652. };
  29653. /**
  29654. * The byte type.
  29655. */
  29656. VertexBuffer.BYTE = 5120;
  29657. /**
  29658. * The unsigned byte type.
  29659. */
  29660. VertexBuffer.UNSIGNED_BYTE = 5121;
  29661. /**
  29662. * The short type.
  29663. */
  29664. VertexBuffer.SHORT = 5122;
  29665. /**
  29666. * The unsigned short type.
  29667. */
  29668. VertexBuffer.UNSIGNED_SHORT = 5123;
  29669. /**
  29670. * The integer type.
  29671. */
  29672. VertexBuffer.INT = 5124;
  29673. /**
  29674. * The unsigned integer type.
  29675. */
  29676. VertexBuffer.UNSIGNED_INT = 5125;
  29677. /**
  29678. * The float type.
  29679. */
  29680. VertexBuffer.FLOAT = 5126;
  29681. // Enums
  29682. VertexBuffer._PositionKind = "position";
  29683. VertexBuffer._NormalKind = "normal";
  29684. VertexBuffer._TangentKind = "tangent";
  29685. VertexBuffer._UVKind = "uv";
  29686. VertexBuffer._UV2Kind = "uv2";
  29687. VertexBuffer._UV3Kind = "uv3";
  29688. VertexBuffer._UV4Kind = "uv4";
  29689. VertexBuffer._UV5Kind = "uv5";
  29690. VertexBuffer._UV6Kind = "uv6";
  29691. VertexBuffer._ColorKind = "color";
  29692. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29693. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29694. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29695. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29696. return VertexBuffer;
  29697. }());
  29698. BABYLON.VertexBuffer = VertexBuffer;
  29699. })(BABYLON || (BABYLON = {}));
  29700. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29701. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29702. var BABYLON;
  29703. (function (BABYLON) {
  29704. /**
  29705. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29706. */
  29707. var DummyInternalTextureTracker = /** @class */ (function () {
  29708. function DummyInternalTextureTracker() {
  29709. /**
  29710. * Gets or set the previous tracker in the list
  29711. */
  29712. this.previous = null;
  29713. /**
  29714. * Gets or set the next tracker in the list
  29715. */
  29716. this.next = null;
  29717. }
  29718. return DummyInternalTextureTracker;
  29719. }());
  29720. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29721. })(BABYLON || (BABYLON = {}));
  29722. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29723. var BABYLON;
  29724. (function (BABYLON) {
  29725. /**
  29726. * Class used to store data associated with WebGL texture data for the engine
  29727. * This class should not be used directly
  29728. */
  29729. var InternalTexture = /** @class */ (function () {
  29730. /**
  29731. * Creates a new InternalTexture
  29732. * @param engine defines the engine to use
  29733. * @param dataSource defines the type of data that will be used
  29734. */
  29735. function InternalTexture(engine, dataSource) {
  29736. /**
  29737. * Observable called when the texture is loaded
  29738. */
  29739. this.onLoadedObservable = new BABYLON.Observable();
  29740. /**
  29741. * Gets or set the previous tracker in the list
  29742. */
  29743. this.previous = null;
  29744. /**
  29745. * Gets or set the next tracker in the list
  29746. */
  29747. this.next = null;
  29748. // Private
  29749. /** @hidden */
  29750. this._initialSlot = -1;
  29751. /** @hidden */
  29752. this._designatedSlot = -1;
  29753. /** @hidden */
  29754. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29755. /** @hidden */
  29756. this._comparisonFunction = 0;
  29757. /** @hidden */
  29758. this._sphericalPolynomial = null;
  29759. /** @hidden */
  29760. this._lodGenerationScale = 0;
  29761. /** @hidden */
  29762. this._lodGenerationOffset = 0;
  29763. /** @hidden */
  29764. this._isRGBD = false;
  29765. /** @hidden */
  29766. this._references = 1;
  29767. this._engine = engine;
  29768. this._dataSource = dataSource;
  29769. this._webGLTexture = engine._createTexture();
  29770. }
  29771. /**
  29772. * Gets the Engine the texture belongs to.
  29773. * @returns The babylon engine
  29774. */
  29775. InternalTexture.prototype.getEngine = function () {
  29776. return this._engine;
  29777. };
  29778. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29779. /**
  29780. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29781. */
  29782. get: function () {
  29783. return this._dataSource;
  29784. },
  29785. enumerable: true,
  29786. configurable: true
  29787. });
  29788. /**
  29789. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29790. */
  29791. InternalTexture.prototype.incrementReferences = function () {
  29792. this._references++;
  29793. };
  29794. /**
  29795. * Change the size of the texture (not the size of the content)
  29796. * @param width defines the new width
  29797. * @param height defines the new height
  29798. * @param depth defines the new depth (1 by default)
  29799. */
  29800. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29801. if (depth === void 0) { depth = 1; }
  29802. this.width = width;
  29803. this.height = height;
  29804. this.depth = depth;
  29805. this.baseWidth = width;
  29806. this.baseHeight = height;
  29807. this.baseDepth = depth;
  29808. this._size = width * height * depth;
  29809. };
  29810. /** @hidden */
  29811. InternalTexture.prototype._rebuild = function () {
  29812. var _this = this;
  29813. var proxy;
  29814. this.isReady = false;
  29815. this._cachedCoordinatesMode = null;
  29816. this._cachedWrapU = null;
  29817. this._cachedWrapV = null;
  29818. this._cachedAnisotropicFilteringLevel = null;
  29819. switch (this._dataSource) {
  29820. case InternalTexture.DATASOURCE_TEMP:
  29821. return;
  29822. case InternalTexture.DATASOURCE_URL:
  29823. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29824. _this.isReady = true;
  29825. }, null, this._buffer, undefined, this.format);
  29826. proxy._swapAndDie(this);
  29827. return;
  29828. case InternalTexture.DATASOURCE_RAW:
  29829. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29830. proxy._swapAndDie(this);
  29831. this.isReady = true;
  29832. return;
  29833. case InternalTexture.DATASOURCE_RAW3D:
  29834. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29835. proxy._swapAndDie(this);
  29836. this.isReady = true;
  29837. return;
  29838. case InternalTexture.DATASOURCE_DYNAMIC:
  29839. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29840. proxy._swapAndDie(this);
  29841. // The engine will make sure to update content so no need to flag it as isReady = true
  29842. return;
  29843. case InternalTexture.DATASOURCE_RENDERTARGET:
  29844. var options = new BABYLON.RenderTargetCreationOptions();
  29845. options.generateDepthBuffer = this._generateDepthBuffer;
  29846. options.generateMipMaps = this.generateMipMaps;
  29847. options.generateStencilBuffer = this._generateStencilBuffer;
  29848. options.samplingMode = this.samplingMode;
  29849. options.type = this.type;
  29850. if (this.isCube) {
  29851. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29852. }
  29853. else {
  29854. var size = {
  29855. width: this.width,
  29856. height: this.height
  29857. };
  29858. proxy = this._engine.createRenderTargetTexture(size, options);
  29859. }
  29860. proxy._swapAndDie(this);
  29861. this.isReady = true;
  29862. return;
  29863. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29864. var depthTextureOptions = {
  29865. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29866. comparisonFunction: this._comparisonFunction,
  29867. generateStencil: this._generateStencilBuffer,
  29868. isCube: this.isCube
  29869. };
  29870. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29871. proxy._swapAndDie(this);
  29872. this.isReady = true;
  29873. return;
  29874. case InternalTexture.DATASOURCE_CUBE:
  29875. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29876. _this.isReady = true;
  29877. }, null, this.format, this._extension);
  29878. proxy._swapAndDie(this);
  29879. return;
  29880. case InternalTexture.DATASOURCE_CUBERAW:
  29881. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29882. proxy._swapAndDie(this);
  29883. this.isReady = true;
  29884. return;
  29885. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29886. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29887. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29888. _this.isReady = true;
  29889. });
  29890. proxy._swapAndDie(this);
  29891. return;
  29892. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29893. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29894. if (proxy) {
  29895. proxy._swapAndDie(_this);
  29896. }
  29897. _this.isReady = true;
  29898. }, null, this.format, this._extension);
  29899. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29900. return;
  29901. }
  29902. };
  29903. /** @hidden */
  29904. InternalTexture.prototype._swapAndDie = function (target) {
  29905. target._webGLTexture = this._webGLTexture;
  29906. if (this._framebuffer) {
  29907. target._framebuffer = this._framebuffer;
  29908. }
  29909. if (this._depthStencilBuffer) {
  29910. target._depthStencilBuffer = this._depthStencilBuffer;
  29911. }
  29912. if (this._lodTextureHigh) {
  29913. if (target._lodTextureHigh) {
  29914. target._lodTextureHigh.dispose();
  29915. }
  29916. target._lodTextureHigh = this._lodTextureHigh;
  29917. }
  29918. if (this._lodTextureMid) {
  29919. if (target._lodTextureMid) {
  29920. target._lodTextureMid.dispose();
  29921. }
  29922. target._lodTextureMid = this._lodTextureMid;
  29923. }
  29924. if (this._lodTextureLow) {
  29925. if (target._lodTextureLow) {
  29926. target._lodTextureLow.dispose();
  29927. }
  29928. target._lodTextureLow = this._lodTextureLow;
  29929. }
  29930. var cache = this._engine.getLoadedTexturesCache();
  29931. var index = cache.indexOf(this);
  29932. if (index !== -1) {
  29933. cache.splice(index, 1);
  29934. }
  29935. };
  29936. /**
  29937. * Dispose the current allocated resources
  29938. */
  29939. InternalTexture.prototype.dispose = function () {
  29940. if (!this._webGLTexture) {
  29941. return;
  29942. }
  29943. this._references--;
  29944. if (this._references === 0) {
  29945. this._engine._releaseTexture(this);
  29946. this._webGLTexture = null;
  29947. this.previous = null;
  29948. this.next = null;
  29949. }
  29950. };
  29951. /**
  29952. * The source of the texture data is unknown
  29953. */
  29954. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29955. /**
  29956. * Texture data comes from an URL
  29957. */
  29958. InternalTexture.DATASOURCE_URL = 1;
  29959. /**
  29960. * Texture data is only used for temporary storage
  29961. */
  29962. InternalTexture.DATASOURCE_TEMP = 2;
  29963. /**
  29964. * Texture data comes from raw data (ArrayBuffer)
  29965. */
  29966. InternalTexture.DATASOURCE_RAW = 3;
  29967. /**
  29968. * Texture content is dynamic (video or dynamic texture)
  29969. */
  29970. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29971. /**
  29972. * Texture content is generated by rendering to it
  29973. */
  29974. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29975. /**
  29976. * Texture content is part of a multi render target process
  29977. */
  29978. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29979. /**
  29980. * Texture data comes from a cube data file
  29981. */
  29982. InternalTexture.DATASOURCE_CUBE = 7;
  29983. /**
  29984. * Texture data comes from a raw cube data
  29985. */
  29986. InternalTexture.DATASOURCE_CUBERAW = 8;
  29987. /**
  29988. * Texture data come from a prefiltered cube data file
  29989. */
  29990. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29991. /**
  29992. * Texture content is raw 3D data
  29993. */
  29994. InternalTexture.DATASOURCE_RAW3D = 10;
  29995. /**
  29996. * Texture content is a depth texture
  29997. */
  29998. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29999. /**
  30000. * Texture data comes from a raw cube data encoded with RGBD
  30001. */
  30002. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30003. return InternalTexture;
  30004. }());
  30005. BABYLON.InternalTexture = InternalTexture;
  30006. })(BABYLON || (BABYLON = {}));
  30007. //# sourceMappingURL=babylon.internalTexture.js.map
  30008. var BABYLON;
  30009. (function (BABYLON) {
  30010. var BaseTexture = /** @class */ (function () {
  30011. function BaseTexture(scene) {
  30012. this._hasAlpha = false;
  30013. this.getAlphaFromRGB = false;
  30014. this.level = 1;
  30015. this.coordinatesIndex = 0;
  30016. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30017. /**
  30018. * | Value | Type | Description |
  30019. * | ----- | ------------------ | ----------- |
  30020. * | 0 | CLAMP_ADDRESSMODE | |
  30021. * | 1 | WRAP_ADDRESSMODE | |
  30022. * | 2 | MIRROR_ADDRESSMODE | |
  30023. */
  30024. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30025. /**
  30026. * | Value | Type | Description |
  30027. * | ----- | ------------------ | ----------- |
  30028. * | 0 | CLAMP_ADDRESSMODE | |
  30029. * | 1 | WRAP_ADDRESSMODE | |
  30030. * | 2 | MIRROR_ADDRESSMODE | |
  30031. */
  30032. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30033. /**
  30034. * | Value | Type | Description |
  30035. * | ----- | ------------------ | ----------- |
  30036. * | 0 | CLAMP_ADDRESSMODE | |
  30037. * | 1 | WRAP_ADDRESSMODE | |
  30038. * | 2 | MIRROR_ADDRESSMODE | |
  30039. */
  30040. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30041. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30042. this.isCube = false;
  30043. this.is3D = false;
  30044. this.gammaSpace = true;
  30045. this.invertZ = false;
  30046. this.lodLevelInAlpha = false;
  30047. this.isRenderTarget = false;
  30048. this.animations = new Array();
  30049. /**
  30050. * An event triggered when the texture is disposed.
  30051. */
  30052. this.onDisposeObservable = new BABYLON.Observable();
  30053. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30054. this._cachedSize = BABYLON.Size.Zero();
  30055. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30056. if (this._scene) {
  30057. this._scene.textures.push(this);
  30058. }
  30059. this._uid = null;
  30060. }
  30061. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30062. get: function () {
  30063. return this._hasAlpha;
  30064. },
  30065. set: function (value) {
  30066. if (this._hasAlpha === value) {
  30067. return;
  30068. }
  30069. this._hasAlpha = value;
  30070. if (this._scene) {
  30071. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30072. }
  30073. },
  30074. enumerable: true,
  30075. configurable: true
  30076. });
  30077. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30078. get: function () {
  30079. return this._coordinatesMode;
  30080. },
  30081. /**
  30082. * How a texture is mapped.
  30083. *
  30084. * | Value | Type | Description |
  30085. * | ----- | ----------------------------------- | ----------- |
  30086. * | 0 | EXPLICIT_MODE | |
  30087. * | 1 | SPHERICAL_MODE | |
  30088. * | 2 | PLANAR_MODE | |
  30089. * | 3 | CUBIC_MODE | |
  30090. * | 4 | PROJECTION_MODE | |
  30091. * | 5 | SKYBOX_MODE | |
  30092. * | 6 | INVCUBIC_MODE | |
  30093. * | 7 | EQUIRECTANGULAR_MODE | |
  30094. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30095. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30096. */
  30097. set: function (value) {
  30098. if (this._coordinatesMode === value) {
  30099. return;
  30100. }
  30101. this._coordinatesMode = value;
  30102. if (this._scene) {
  30103. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30104. }
  30105. },
  30106. enumerable: true,
  30107. configurable: true
  30108. });
  30109. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30110. /**
  30111. * Gets whether or not the texture contains RGBD data.
  30112. */
  30113. get: function () {
  30114. return this._texture != null && this._texture._isRGBD;
  30115. },
  30116. enumerable: true,
  30117. configurable: true
  30118. });
  30119. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30120. get: function () {
  30121. if (this._texture)
  30122. return this._texture._lodGenerationOffset;
  30123. return 0.0;
  30124. },
  30125. set: function (value) {
  30126. if (this._texture)
  30127. this._texture._lodGenerationOffset = value;
  30128. },
  30129. enumerable: true,
  30130. configurable: true
  30131. });
  30132. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30133. get: function () {
  30134. if (this._texture)
  30135. return this._texture._lodGenerationScale;
  30136. return 0.0;
  30137. },
  30138. set: function (value) {
  30139. if (this._texture)
  30140. this._texture._lodGenerationScale = value;
  30141. },
  30142. enumerable: true,
  30143. configurable: true
  30144. });
  30145. Object.defineProperty(BaseTexture.prototype, "uid", {
  30146. get: function () {
  30147. if (!this._uid) {
  30148. this._uid = BABYLON.Tools.RandomId();
  30149. }
  30150. return this._uid;
  30151. },
  30152. enumerable: true,
  30153. configurable: true
  30154. });
  30155. BaseTexture.prototype.toString = function () {
  30156. return this.name;
  30157. };
  30158. BaseTexture.prototype.getClassName = function () {
  30159. return "BaseTexture";
  30160. };
  30161. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30162. set: function (callback) {
  30163. if (this._onDisposeObserver) {
  30164. this.onDisposeObservable.remove(this._onDisposeObserver);
  30165. }
  30166. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30167. },
  30168. enumerable: true,
  30169. configurable: true
  30170. });
  30171. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30172. get: function () {
  30173. return true;
  30174. },
  30175. enumerable: true,
  30176. configurable: true
  30177. });
  30178. BaseTexture.prototype.getScene = function () {
  30179. return this._scene;
  30180. };
  30181. BaseTexture.prototype.getTextureMatrix = function () {
  30182. return BABYLON.Matrix.IdentityReadOnly;
  30183. };
  30184. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30185. return BABYLON.Matrix.IdentityReadOnly;
  30186. };
  30187. BaseTexture.prototype.getInternalTexture = function () {
  30188. return this._texture;
  30189. };
  30190. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30191. return !this.isBlocking || this.isReady();
  30192. };
  30193. BaseTexture.prototype.isReady = function () {
  30194. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30195. this.delayLoad();
  30196. return false;
  30197. }
  30198. if (this._texture) {
  30199. return this._texture.isReady;
  30200. }
  30201. return false;
  30202. };
  30203. BaseTexture.prototype.getSize = function () {
  30204. if (this._texture) {
  30205. if (this._texture.width) {
  30206. this._cachedSize.width = this._texture.width;
  30207. this._cachedSize.height = this._texture.height;
  30208. return this._cachedSize;
  30209. }
  30210. if (this._texture._size) {
  30211. this._cachedSize.width = this._texture._size;
  30212. this._cachedSize.height = this._texture._size;
  30213. return this._cachedSize;
  30214. }
  30215. }
  30216. return this._cachedSize;
  30217. };
  30218. BaseTexture.prototype.getBaseSize = function () {
  30219. if (!this.isReady() || !this._texture)
  30220. return BABYLON.Size.Zero();
  30221. if (this._texture._size) {
  30222. return new BABYLON.Size(this._texture._size, this._texture._size);
  30223. }
  30224. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30225. };
  30226. BaseTexture.prototype.scale = function (ratio) {
  30227. };
  30228. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30229. get: function () {
  30230. return false;
  30231. },
  30232. enumerable: true,
  30233. configurable: true
  30234. });
  30235. /** @hidden */
  30236. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30237. if (!this._scene) {
  30238. return null;
  30239. }
  30240. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30241. for (var index = 0; index < texturesCache.length; index++) {
  30242. var texturesCacheEntry = texturesCache[index];
  30243. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30244. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30245. texturesCacheEntry.incrementReferences();
  30246. return texturesCacheEntry;
  30247. }
  30248. }
  30249. }
  30250. return null;
  30251. };
  30252. /** @hidden */
  30253. BaseTexture.prototype._rebuild = function () {
  30254. };
  30255. BaseTexture.prototype.delayLoad = function () {
  30256. };
  30257. BaseTexture.prototype.clone = function () {
  30258. return null;
  30259. };
  30260. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30261. get: function () {
  30262. if (!this._texture) {
  30263. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30264. }
  30265. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30266. },
  30267. enumerable: true,
  30268. configurable: true
  30269. });
  30270. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30271. get: function () {
  30272. if (!this._texture) {
  30273. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30274. }
  30275. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30276. },
  30277. enumerable: true,
  30278. configurable: true
  30279. });
  30280. /**
  30281. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30282. * This will returns an RGBA array buffer containing either in values (0-255) or
  30283. * float values (0-1) depending of the underlying buffer type.
  30284. * @param faceIndex The face of the texture to read (in case of cube texture)
  30285. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30286. * @returns The Array buffer containing the pixels data.
  30287. */
  30288. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30289. if (faceIndex === void 0) { faceIndex = 0; }
  30290. if (level === void 0) { level = 0; }
  30291. if (!this._texture) {
  30292. return null;
  30293. }
  30294. var size = this.getSize();
  30295. var width = size.width;
  30296. var height = size.height;
  30297. var scene = this.getScene();
  30298. if (!scene) {
  30299. return null;
  30300. }
  30301. var engine = scene.getEngine();
  30302. if (level != 0) {
  30303. width = width / Math.pow(2, level);
  30304. height = height / Math.pow(2, level);
  30305. width = Math.round(width);
  30306. height = Math.round(height);
  30307. }
  30308. if (this._texture.isCube) {
  30309. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30310. }
  30311. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30312. };
  30313. BaseTexture.prototype.releaseInternalTexture = function () {
  30314. if (this._texture) {
  30315. this._texture.dispose();
  30316. this._texture = null;
  30317. }
  30318. };
  30319. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30320. get: function () {
  30321. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30322. return null;
  30323. }
  30324. if (!this._texture._sphericalPolynomial) {
  30325. this._texture._sphericalPolynomial =
  30326. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30327. }
  30328. return this._texture._sphericalPolynomial;
  30329. },
  30330. set: function (value) {
  30331. if (this._texture) {
  30332. this._texture._sphericalPolynomial = value;
  30333. }
  30334. },
  30335. enumerable: true,
  30336. configurable: true
  30337. });
  30338. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30339. get: function () {
  30340. if (this._texture) {
  30341. return this._texture._lodTextureHigh;
  30342. }
  30343. return null;
  30344. },
  30345. enumerable: true,
  30346. configurable: true
  30347. });
  30348. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30349. get: function () {
  30350. if (this._texture) {
  30351. return this._texture._lodTextureMid;
  30352. }
  30353. return null;
  30354. },
  30355. enumerable: true,
  30356. configurable: true
  30357. });
  30358. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30359. get: function () {
  30360. if (this._texture) {
  30361. return this._texture._lodTextureLow;
  30362. }
  30363. return null;
  30364. },
  30365. enumerable: true,
  30366. configurable: true
  30367. });
  30368. BaseTexture.prototype.dispose = function () {
  30369. if (!this._scene) {
  30370. return;
  30371. }
  30372. // Animations
  30373. this._scene.stopAnimation(this);
  30374. // Remove from scene
  30375. this._scene._removePendingData(this);
  30376. var index = this._scene.textures.indexOf(this);
  30377. if (index >= 0) {
  30378. this._scene.textures.splice(index, 1);
  30379. }
  30380. if (this._texture === undefined) {
  30381. return;
  30382. }
  30383. // Release
  30384. this.releaseInternalTexture();
  30385. // Callback
  30386. this.onDisposeObservable.notifyObservers(this);
  30387. this.onDisposeObservable.clear();
  30388. };
  30389. BaseTexture.prototype.serialize = function () {
  30390. if (!this.name) {
  30391. return null;
  30392. }
  30393. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30394. // Animations
  30395. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30396. return serializationObject;
  30397. };
  30398. BaseTexture.WhenAllReady = function (textures, callback) {
  30399. var numRemaining = textures.length;
  30400. if (numRemaining === 0) {
  30401. callback();
  30402. return;
  30403. }
  30404. var _loop_1 = function () {
  30405. texture = textures[i];
  30406. if (texture.isReady()) {
  30407. if (--numRemaining === 0) {
  30408. callback();
  30409. }
  30410. }
  30411. else {
  30412. onLoadObservable = texture.onLoadObservable;
  30413. var onLoadCallback_1 = function () {
  30414. onLoadObservable.removeCallback(onLoadCallback_1);
  30415. if (--numRemaining === 0) {
  30416. callback();
  30417. }
  30418. };
  30419. onLoadObservable.add(onLoadCallback_1);
  30420. }
  30421. };
  30422. var texture, onLoadObservable;
  30423. for (var i = 0; i < textures.length; i++) {
  30424. _loop_1();
  30425. }
  30426. };
  30427. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30428. __decorate([
  30429. BABYLON.serialize()
  30430. ], BaseTexture.prototype, "name", void 0);
  30431. __decorate([
  30432. BABYLON.serialize("hasAlpha")
  30433. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30434. __decorate([
  30435. BABYLON.serialize()
  30436. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30437. __decorate([
  30438. BABYLON.serialize()
  30439. ], BaseTexture.prototype, "level", void 0);
  30440. __decorate([
  30441. BABYLON.serialize()
  30442. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30443. __decorate([
  30444. BABYLON.serialize("coordinatesMode")
  30445. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30446. __decorate([
  30447. BABYLON.serialize()
  30448. ], BaseTexture.prototype, "wrapU", void 0);
  30449. __decorate([
  30450. BABYLON.serialize()
  30451. ], BaseTexture.prototype, "wrapV", void 0);
  30452. __decorate([
  30453. BABYLON.serialize()
  30454. ], BaseTexture.prototype, "wrapR", void 0);
  30455. __decorate([
  30456. BABYLON.serialize()
  30457. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30458. __decorate([
  30459. BABYLON.serialize()
  30460. ], BaseTexture.prototype, "isCube", void 0);
  30461. __decorate([
  30462. BABYLON.serialize()
  30463. ], BaseTexture.prototype, "is3D", void 0);
  30464. __decorate([
  30465. BABYLON.serialize()
  30466. ], BaseTexture.prototype, "gammaSpace", void 0);
  30467. __decorate([
  30468. BABYLON.serialize()
  30469. ], BaseTexture.prototype, "invertZ", void 0);
  30470. __decorate([
  30471. BABYLON.serialize()
  30472. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30473. __decorate([
  30474. BABYLON.serialize()
  30475. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30476. __decorate([
  30477. BABYLON.serialize()
  30478. ], BaseTexture.prototype, "lodGenerationScale", null);
  30479. __decorate([
  30480. BABYLON.serialize()
  30481. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30482. return BaseTexture;
  30483. }());
  30484. BABYLON.BaseTexture = BaseTexture;
  30485. })(BABYLON || (BABYLON = {}));
  30486. //# sourceMappingURL=babylon.baseTexture.js.map
  30487. var BABYLON;
  30488. (function (BABYLON) {
  30489. var Texture = /** @class */ (function (_super) {
  30490. __extends(Texture, _super);
  30491. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30492. if (noMipmap === void 0) { noMipmap = false; }
  30493. if (invertY === void 0) { invertY = true; }
  30494. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30495. if (onLoad === void 0) { onLoad = null; }
  30496. if (onError === void 0) { onError = null; }
  30497. if (buffer === void 0) { buffer = null; }
  30498. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30499. var _this = _super.call(this, scene) || this;
  30500. _this.uOffset = 0;
  30501. _this.vOffset = 0;
  30502. _this.uScale = 1.0;
  30503. _this.vScale = 1.0;
  30504. _this.uAng = 0;
  30505. _this.vAng = 0;
  30506. _this.wAng = 0;
  30507. /**
  30508. * Defines the center of rotation (U)
  30509. */
  30510. _this.uRotationCenter = 0.5;
  30511. /**
  30512. * Defines the center of rotation (V)
  30513. */
  30514. _this.vRotationCenter = 0.5;
  30515. /**
  30516. * Defines the center of rotation (W)
  30517. */
  30518. _this.wRotationCenter = 0.5;
  30519. _this._isBlocking = true;
  30520. _this.name = url || "";
  30521. _this.url = url;
  30522. _this._noMipmap = noMipmap;
  30523. _this._invertY = invertY;
  30524. _this._samplingMode = samplingMode;
  30525. _this._buffer = buffer;
  30526. _this._deleteBuffer = deleteBuffer;
  30527. if (format) {
  30528. _this._format = format;
  30529. }
  30530. scene = _this.getScene();
  30531. if (!scene) {
  30532. return _this;
  30533. }
  30534. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30535. var load = function () {
  30536. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30537. _this.onLoadObservable.notifyObservers(_this);
  30538. }
  30539. if (onLoad) {
  30540. onLoad();
  30541. }
  30542. if (!_this.isBlocking && scene) {
  30543. scene.resetCachedMaterial();
  30544. }
  30545. };
  30546. if (!_this.url) {
  30547. _this._delayedOnLoad = load;
  30548. _this._delayedOnError = onError;
  30549. return _this;
  30550. }
  30551. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30552. if (!_this._texture) {
  30553. if (!scene.useDelayedTextureLoading) {
  30554. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30555. if (deleteBuffer) {
  30556. delete _this._buffer;
  30557. }
  30558. }
  30559. else {
  30560. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30561. _this._delayedOnLoad = load;
  30562. _this._delayedOnError = onError;
  30563. }
  30564. }
  30565. else {
  30566. if (_this._texture.isReady) {
  30567. BABYLON.Tools.SetImmediate(function () { return load(); });
  30568. }
  30569. else {
  30570. _this._texture.onLoadedObservable.add(load);
  30571. }
  30572. }
  30573. return _this;
  30574. }
  30575. Object.defineProperty(Texture.prototype, "noMipmap", {
  30576. get: function () {
  30577. return this._noMipmap;
  30578. },
  30579. enumerable: true,
  30580. configurable: true
  30581. });
  30582. Object.defineProperty(Texture.prototype, "isBlocking", {
  30583. get: function () {
  30584. return this._isBlocking;
  30585. },
  30586. set: function (value) {
  30587. this._isBlocking = value;
  30588. },
  30589. enumerable: true,
  30590. configurable: true
  30591. });
  30592. Object.defineProperty(Texture.prototype, "samplingMode", {
  30593. get: function () {
  30594. return this._samplingMode;
  30595. },
  30596. enumerable: true,
  30597. configurable: true
  30598. });
  30599. /**
  30600. * Update the url (and optional buffer) of this texture if url was null during construction.
  30601. * @param url the url of the texture
  30602. * @param buffer the buffer of the texture (defaults to null)
  30603. */
  30604. Texture.prototype.updateURL = function (url, buffer) {
  30605. if (buffer === void 0) { buffer = null; }
  30606. if (this.url) {
  30607. throw new Error("URL is already set");
  30608. }
  30609. this.url = url;
  30610. this._buffer = buffer;
  30611. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30612. this.delayLoad();
  30613. };
  30614. Texture.prototype.delayLoad = function () {
  30615. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30616. return;
  30617. }
  30618. var scene = this.getScene();
  30619. if (!scene) {
  30620. return;
  30621. }
  30622. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30623. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30624. if (!this._texture) {
  30625. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30626. if (this._deleteBuffer) {
  30627. delete this._buffer;
  30628. }
  30629. }
  30630. else {
  30631. if (this._delayedOnLoad) {
  30632. if (this._texture.isReady) {
  30633. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30634. }
  30635. else {
  30636. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30637. }
  30638. }
  30639. }
  30640. this._delayedOnLoad = null;
  30641. this._delayedOnError = null;
  30642. };
  30643. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30644. if (!this._texture) {
  30645. return;
  30646. }
  30647. var scene = this.getScene();
  30648. if (!scene) {
  30649. return;
  30650. }
  30651. this._samplingMode = samplingMode;
  30652. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30653. };
  30654. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30655. x *= this.uScale;
  30656. y *= this.vScale;
  30657. x -= this.uRotationCenter * this.uScale;
  30658. y -= this.vRotationCenter * this.vScale;
  30659. z -= this.wRotationCenter;
  30660. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30661. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30662. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30663. t.z += this.wRotationCenter;
  30664. };
  30665. Texture.prototype.getTextureMatrix = function () {
  30666. var _this = this;
  30667. if (this.uOffset === this._cachedUOffset &&
  30668. this.vOffset === this._cachedVOffset &&
  30669. this.uScale === this._cachedUScale &&
  30670. this.vScale === this._cachedVScale &&
  30671. this.uAng === this._cachedUAng &&
  30672. this.vAng === this._cachedVAng &&
  30673. this.wAng === this._cachedWAng) {
  30674. return this._cachedTextureMatrix;
  30675. }
  30676. this._cachedUOffset = this.uOffset;
  30677. this._cachedVOffset = this.vOffset;
  30678. this._cachedUScale = this.uScale;
  30679. this._cachedVScale = this.vScale;
  30680. this._cachedUAng = this.uAng;
  30681. this._cachedVAng = this.vAng;
  30682. this._cachedWAng = this.wAng;
  30683. if (!this._cachedTextureMatrix) {
  30684. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30685. this._rowGenerationMatrix = new BABYLON.Matrix();
  30686. this._t0 = BABYLON.Vector3.Zero();
  30687. this._t1 = BABYLON.Vector3.Zero();
  30688. this._t2 = BABYLON.Vector3.Zero();
  30689. }
  30690. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30691. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30692. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30693. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30694. this._t1.subtractInPlace(this._t0);
  30695. this._t2.subtractInPlace(this._t0);
  30696. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30697. this._cachedTextureMatrix.m[0] = this._t1.x;
  30698. this._cachedTextureMatrix.m[1] = this._t1.y;
  30699. this._cachedTextureMatrix.m[2] = this._t1.z;
  30700. this._cachedTextureMatrix.m[4] = this._t2.x;
  30701. this._cachedTextureMatrix.m[5] = this._t2.y;
  30702. this._cachedTextureMatrix.m[6] = this._t2.z;
  30703. this._cachedTextureMatrix.m[8] = this._t0.x;
  30704. this._cachedTextureMatrix.m[9] = this._t0.y;
  30705. this._cachedTextureMatrix.m[10] = this._t0.z;
  30706. var scene = this.getScene();
  30707. if (!scene) {
  30708. return this._cachedTextureMatrix;
  30709. }
  30710. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30711. return mat.hasTexture(_this);
  30712. });
  30713. return this._cachedTextureMatrix;
  30714. };
  30715. Texture.prototype.getReflectionTextureMatrix = function () {
  30716. var _this = this;
  30717. var scene = this.getScene();
  30718. if (!scene) {
  30719. return this._cachedTextureMatrix;
  30720. }
  30721. if (this.uOffset === this._cachedUOffset &&
  30722. this.vOffset === this._cachedVOffset &&
  30723. this.uScale === this._cachedUScale &&
  30724. this.vScale === this._cachedVScale &&
  30725. this.coordinatesMode === this._cachedCoordinatesMode) {
  30726. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30727. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30728. return this._cachedTextureMatrix;
  30729. }
  30730. }
  30731. else {
  30732. return this._cachedTextureMatrix;
  30733. }
  30734. }
  30735. if (!this._cachedTextureMatrix) {
  30736. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30737. }
  30738. if (!this._projectionModeMatrix) {
  30739. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30740. }
  30741. this._cachedUOffset = this.uOffset;
  30742. this._cachedVOffset = this.vOffset;
  30743. this._cachedUScale = this.uScale;
  30744. this._cachedVScale = this.vScale;
  30745. this._cachedCoordinatesMode = this.coordinatesMode;
  30746. switch (this.coordinatesMode) {
  30747. case Texture.PLANAR_MODE:
  30748. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30749. this._cachedTextureMatrix[0] = this.uScale;
  30750. this._cachedTextureMatrix[5] = this.vScale;
  30751. this._cachedTextureMatrix[12] = this.uOffset;
  30752. this._cachedTextureMatrix[13] = this.vOffset;
  30753. break;
  30754. case Texture.PROJECTION_MODE:
  30755. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30756. this._projectionModeMatrix.m[0] = 0.5;
  30757. this._projectionModeMatrix.m[5] = -0.5;
  30758. this._projectionModeMatrix.m[10] = 0.0;
  30759. this._projectionModeMatrix.m[12] = 0.5;
  30760. this._projectionModeMatrix.m[13] = 0.5;
  30761. this._projectionModeMatrix.m[14] = 1.0;
  30762. this._projectionModeMatrix.m[15] = 1.0;
  30763. var projectionMatrix = scene.getProjectionMatrix();
  30764. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30765. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30766. break;
  30767. default:
  30768. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30769. break;
  30770. }
  30771. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30772. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30773. });
  30774. return this._cachedTextureMatrix;
  30775. };
  30776. Texture.prototype.clone = function () {
  30777. var _this = this;
  30778. return BABYLON.SerializationHelper.Clone(function () {
  30779. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30780. }, this);
  30781. };
  30782. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30783. get: function () {
  30784. if (!this._onLoadObservable) {
  30785. this._onLoadObservable = new BABYLON.Observable();
  30786. }
  30787. return this._onLoadObservable;
  30788. },
  30789. enumerable: true,
  30790. configurable: true
  30791. });
  30792. Texture.prototype.serialize = function () {
  30793. var serializationObject = _super.prototype.serialize.call(this);
  30794. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30795. serializationObject.base64String = this._buffer;
  30796. serializationObject.name = serializationObject.name.replace("data:", "");
  30797. }
  30798. serializationObject.invertY = this._invertY;
  30799. serializationObject.samplingMode = this.samplingMode;
  30800. return serializationObject;
  30801. };
  30802. Texture.prototype.getClassName = function () {
  30803. return "Texture";
  30804. };
  30805. Texture.prototype.dispose = function () {
  30806. _super.prototype.dispose.call(this);
  30807. if (this._onLoadObservable) {
  30808. this._onLoadObservable.clear();
  30809. this._onLoadObservable = null;
  30810. }
  30811. this._delayedOnLoad = null;
  30812. this._delayedOnError = null;
  30813. };
  30814. // Statics
  30815. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30816. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30817. if (onLoad === void 0) { onLoad = null; }
  30818. if (onError === void 0) { onError = null; }
  30819. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30820. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30821. };
  30822. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30823. if (parsedTexture.customType) {
  30824. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30825. // Update Sampling Mode
  30826. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30827. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30828. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30829. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30830. }
  30831. }
  30832. return parsedCustomTexture;
  30833. }
  30834. if (parsedTexture.isCube) {
  30835. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30836. }
  30837. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30838. return null;
  30839. }
  30840. var texture = BABYLON.SerializationHelper.Parse(function () {
  30841. var generateMipMaps = true;
  30842. if (parsedTexture.noMipmap) {
  30843. generateMipMaps = false;
  30844. }
  30845. if (parsedTexture.mirrorPlane) {
  30846. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30847. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30848. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30849. return mirrorTexture;
  30850. }
  30851. else if (parsedTexture.isRenderTarget) {
  30852. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30853. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30854. return renderTargetTexture;
  30855. }
  30856. else {
  30857. var texture;
  30858. if (parsedTexture.base64String) {
  30859. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30860. }
  30861. else {
  30862. var url = rootUrl + parsedTexture.name;
  30863. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30864. url = parsedTexture.url;
  30865. }
  30866. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30867. }
  30868. return texture;
  30869. }
  30870. }, parsedTexture, scene);
  30871. // Update Sampling Mode
  30872. if (parsedTexture.samplingMode) {
  30873. var sampling = parsedTexture.samplingMode;
  30874. if (texture._samplingMode !== sampling) {
  30875. texture.updateSamplingMode(sampling);
  30876. }
  30877. }
  30878. // Animations
  30879. if (parsedTexture.animations) {
  30880. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30881. var parsedAnimation = parsedTexture.animations[animationIndex];
  30882. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30883. }
  30884. }
  30885. return texture;
  30886. };
  30887. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30888. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30889. if (noMipmap === void 0) { noMipmap = false; }
  30890. if (invertY === void 0) { invertY = true; }
  30891. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30892. if (onLoad === void 0) { onLoad = null; }
  30893. if (onError === void 0) { onError = null; }
  30894. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30895. if (name.substr(0, 5) !== "data:") {
  30896. name = "data:" + name;
  30897. }
  30898. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30899. };
  30900. // Constants
  30901. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30902. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30903. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30904. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30905. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30906. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30907. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30908. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30909. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30910. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30911. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30912. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30913. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30914. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30915. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30916. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30917. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30918. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30919. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30920. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30921. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30922. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30923. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30924. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30925. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30926. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30927. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30928. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30929. /**
  30930. * 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
  30931. */
  30932. Texture.UseSerializedUrlIfAny = false;
  30933. __decorate([
  30934. BABYLON.serialize()
  30935. ], Texture.prototype, "url", void 0);
  30936. __decorate([
  30937. BABYLON.serialize()
  30938. ], Texture.prototype, "uOffset", void 0);
  30939. __decorate([
  30940. BABYLON.serialize()
  30941. ], Texture.prototype, "vOffset", void 0);
  30942. __decorate([
  30943. BABYLON.serialize()
  30944. ], Texture.prototype, "uScale", void 0);
  30945. __decorate([
  30946. BABYLON.serialize()
  30947. ], Texture.prototype, "vScale", void 0);
  30948. __decorate([
  30949. BABYLON.serialize()
  30950. ], Texture.prototype, "uAng", void 0);
  30951. __decorate([
  30952. BABYLON.serialize()
  30953. ], Texture.prototype, "vAng", void 0);
  30954. __decorate([
  30955. BABYLON.serialize()
  30956. ], Texture.prototype, "wAng", void 0);
  30957. __decorate([
  30958. BABYLON.serialize()
  30959. ], Texture.prototype, "uRotationCenter", void 0);
  30960. __decorate([
  30961. BABYLON.serialize()
  30962. ], Texture.prototype, "vRotationCenter", void 0);
  30963. __decorate([
  30964. BABYLON.serialize()
  30965. ], Texture.prototype, "wRotationCenter", void 0);
  30966. __decorate([
  30967. BABYLON.serialize()
  30968. ], Texture.prototype, "isBlocking", null);
  30969. return Texture;
  30970. }(BABYLON.BaseTexture));
  30971. BABYLON.Texture = Texture;
  30972. })(BABYLON || (BABYLON = {}));
  30973. //# sourceMappingURL=babylon.texture.js.map
  30974. var BABYLON;
  30975. (function (BABYLON) {
  30976. /**
  30977. * @hidden
  30978. **/
  30979. var _InstancesBatch = /** @class */ (function () {
  30980. function _InstancesBatch() {
  30981. this.mustReturn = false;
  30982. this.visibleInstances = new Array();
  30983. this.renderSelf = new Array();
  30984. }
  30985. return _InstancesBatch;
  30986. }());
  30987. BABYLON._InstancesBatch = _InstancesBatch;
  30988. var Mesh = /** @class */ (function (_super) {
  30989. __extends(Mesh, _super);
  30990. /**
  30991. * @constructor
  30992. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30993. * @param {Scene} scene The scene to add this mesh to.
  30994. * @param {Node} parent The parent of this mesh, if it has one
  30995. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30996. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30997. * When false, achieved by calling a clone(), also passing False.
  30998. * This will make creation of children, recursive.
  30999. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31000. */
  31001. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31002. if (scene === void 0) { scene = null; }
  31003. if (parent === void 0) { parent = null; }
  31004. if (source === void 0) { source = null; }
  31005. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31006. var _this = _super.call(this, name, scene) || this;
  31007. // Members
  31008. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31009. _this.instances = new Array();
  31010. _this._LODLevels = new Array();
  31011. /** @hidden */
  31012. _this._visibleInstances = {};
  31013. _this._renderIdForInstances = new Array();
  31014. _this._batchCache = new _InstancesBatch();
  31015. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31016. // Use by builder only to know what orientation were the mesh build in.
  31017. /** @hidden */
  31018. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31019. _this.overrideMaterialSideOrientation = null;
  31020. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31021. // Will be used to save a source mesh reference, If any
  31022. _this._source = null;
  31023. scene = _this.getScene();
  31024. if (source) {
  31025. // Geometry
  31026. if (source._geometry) {
  31027. source._geometry.applyToMesh(_this);
  31028. }
  31029. // Deep copy
  31030. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31031. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31032. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31033. ], ["_poseMatrix"]);
  31034. // Source mesh
  31035. _this._source = source;
  31036. // Metadata
  31037. if (source.metadata && source.metadata.clone) {
  31038. _this.metadata = source.metadata.clone();
  31039. }
  31040. else {
  31041. _this.metadata = source.metadata;
  31042. }
  31043. // Tags
  31044. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31045. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31046. }
  31047. // Parent
  31048. _this.parent = source.parent;
  31049. // Pivot
  31050. _this.setPivotMatrix(source.getPivotMatrix());
  31051. _this.id = name + "." + source.id;
  31052. // Material
  31053. _this.material = source.material;
  31054. var index;
  31055. if (!doNotCloneChildren) {
  31056. // Children
  31057. var directDescendants = source.getDescendants(true);
  31058. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31059. var child = directDescendants[index_1];
  31060. if (child.clone) {
  31061. child.clone(name + "." + child.name, _this);
  31062. }
  31063. }
  31064. }
  31065. // Physics clone
  31066. var physicsEngine = _this.getScene().getPhysicsEngine();
  31067. if (clonePhysicsImpostor && physicsEngine) {
  31068. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31069. if (impostor) {
  31070. _this.physicsImpostor = impostor.clone(_this);
  31071. }
  31072. }
  31073. // Particles
  31074. for (index = 0; index < scene.particleSystems.length; index++) {
  31075. var system = scene.particleSystems[index];
  31076. if (system.emitter === source) {
  31077. system.clone(system.name, _this);
  31078. }
  31079. }
  31080. _this.refreshBoundingInfo();
  31081. _this.computeWorldMatrix(true);
  31082. }
  31083. // Parent
  31084. if (parent !== null) {
  31085. _this.parent = parent;
  31086. }
  31087. return _this;
  31088. }
  31089. Object.defineProperty(Mesh, "FRONTSIDE", {
  31090. /**
  31091. * Mesh side orientation : usually the external or front surface
  31092. */
  31093. get: function () {
  31094. return Mesh._FRONTSIDE;
  31095. },
  31096. enumerable: true,
  31097. configurable: true
  31098. });
  31099. Object.defineProperty(Mesh, "BACKSIDE", {
  31100. /**
  31101. * Mesh side orientation : usually the internal or back surface
  31102. */
  31103. get: function () {
  31104. return Mesh._BACKSIDE;
  31105. },
  31106. enumerable: true,
  31107. configurable: true
  31108. });
  31109. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31110. /**
  31111. * Mesh side orientation : both internal and external or front and back surfaces
  31112. */
  31113. get: function () {
  31114. return Mesh._DOUBLESIDE;
  31115. },
  31116. enumerable: true,
  31117. configurable: true
  31118. });
  31119. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31120. /**
  31121. * Mesh side orientation : by default, `FRONTSIDE`
  31122. */
  31123. get: function () {
  31124. return Mesh._DEFAULTSIDE;
  31125. },
  31126. enumerable: true,
  31127. configurable: true
  31128. });
  31129. Object.defineProperty(Mesh, "NO_CAP", {
  31130. /**
  31131. * Mesh cap setting : no cap
  31132. */
  31133. get: function () {
  31134. return Mesh._NO_CAP;
  31135. },
  31136. enumerable: true,
  31137. configurable: true
  31138. });
  31139. Object.defineProperty(Mesh, "CAP_START", {
  31140. /**
  31141. * Mesh cap setting : one cap at the beginning of the mesh
  31142. */
  31143. get: function () {
  31144. return Mesh._CAP_START;
  31145. },
  31146. enumerable: true,
  31147. configurable: true
  31148. });
  31149. Object.defineProperty(Mesh, "CAP_END", {
  31150. /**
  31151. * Mesh cap setting : one cap at the end of the mesh
  31152. */
  31153. get: function () {
  31154. return Mesh._CAP_END;
  31155. },
  31156. enumerable: true,
  31157. configurable: true
  31158. });
  31159. Object.defineProperty(Mesh, "CAP_ALL", {
  31160. /**
  31161. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31162. */
  31163. get: function () {
  31164. return Mesh._CAP_ALL;
  31165. },
  31166. enumerable: true,
  31167. configurable: true
  31168. });
  31169. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31170. /**
  31171. * An event triggered before rendering the mesh
  31172. */
  31173. get: function () {
  31174. if (!this._onBeforeRenderObservable) {
  31175. this._onBeforeRenderObservable = new BABYLON.Observable();
  31176. }
  31177. return this._onBeforeRenderObservable;
  31178. },
  31179. enumerable: true,
  31180. configurable: true
  31181. });
  31182. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31183. /**
  31184. * An event triggered after rendering the mesh
  31185. */
  31186. get: function () {
  31187. if (!this._onAfterRenderObservable) {
  31188. this._onAfterRenderObservable = new BABYLON.Observable();
  31189. }
  31190. return this._onAfterRenderObservable;
  31191. },
  31192. enumerable: true,
  31193. configurable: true
  31194. });
  31195. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31196. /**
  31197. * An event triggered before drawing the mesh
  31198. */
  31199. get: function () {
  31200. if (!this._onBeforeDrawObservable) {
  31201. this._onBeforeDrawObservable = new BABYLON.Observable();
  31202. }
  31203. return this._onBeforeDrawObservable;
  31204. },
  31205. enumerable: true,
  31206. configurable: true
  31207. });
  31208. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31209. set: function (callback) {
  31210. if (this._onBeforeDrawObserver) {
  31211. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31212. }
  31213. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31214. },
  31215. enumerable: true,
  31216. configurable: true
  31217. });
  31218. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31219. get: function () {
  31220. return this._morphTargetManager;
  31221. },
  31222. set: function (value) {
  31223. if (this._morphTargetManager === value) {
  31224. return;
  31225. }
  31226. this._morphTargetManager = value;
  31227. this._syncGeometryWithMorphTargetManager();
  31228. },
  31229. enumerable: true,
  31230. configurable: true
  31231. });
  31232. Object.defineProperty(Mesh.prototype, "source", {
  31233. get: function () {
  31234. return this._source;
  31235. },
  31236. enumerable: true,
  31237. configurable: true
  31238. });
  31239. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31240. get: function () {
  31241. return this._unIndexed;
  31242. },
  31243. set: function (value) {
  31244. if (this._unIndexed !== value) {
  31245. this._unIndexed = value;
  31246. this._markSubMeshesAsAttributesDirty();
  31247. }
  31248. },
  31249. enumerable: true,
  31250. configurable: true
  31251. });
  31252. // Methods
  31253. /**
  31254. * Returns the string "Mesh".
  31255. */
  31256. Mesh.prototype.getClassName = function () {
  31257. return "Mesh";
  31258. };
  31259. /**
  31260. * Returns a string.
  31261. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31262. */
  31263. Mesh.prototype.toString = function (fullDetails) {
  31264. var ret = _super.prototype.toString.call(this, fullDetails);
  31265. ret += ", n vertices: " + this.getTotalVertices();
  31266. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31267. if (this.animations) {
  31268. for (var i = 0; i < this.animations.length; i++) {
  31269. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31270. }
  31271. }
  31272. if (fullDetails) {
  31273. if (this._geometry) {
  31274. var ib = this.getIndices();
  31275. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31276. if (vb && ib) {
  31277. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31278. }
  31279. }
  31280. else {
  31281. ret += ", flat shading: UNKNOWN";
  31282. }
  31283. }
  31284. return ret;
  31285. };
  31286. /** @hidden */
  31287. Mesh.prototype._unBindEffect = function () {
  31288. _super.prototype._unBindEffect.call(this);
  31289. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31290. var instance = _a[_i];
  31291. instance._unBindEffect();
  31292. }
  31293. };
  31294. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31295. /**
  31296. * True if the mesh has some Levels Of Details (LOD).
  31297. * Returns a boolean.
  31298. */
  31299. get: function () {
  31300. return this._LODLevels.length > 0;
  31301. },
  31302. enumerable: true,
  31303. configurable: true
  31304. });
  31305. /**
  31306. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31307. * @returns an array of {BABYLON.MeshLODLevel}
  31308. */
  31309. Mesh.prototype.getLODLevels = function () {
  31310. return this._LODLevels;
  31311. };
  31312. Mesh.prototype._sortLODLevels = function () {
  31313. this._LODLevels.sort(function (a, b) {
  31314. if (a.distance < b.distance) {
  31315. return 1;
  31316. }
  31317. if (a.distance > b.distance) {
  31318. return -1;
  31319. }
  31320. return 0;
  31321. });
  31322. };
  31323. /**
  31324. * Add a mesh as LOD level triggered at the given distance.
  31325. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31326. * @param distance The distance from the center of the object to show this level
  31327. * @param mesh The mesh to be added as LOD level (can be null)
  31328. * @return This mesh (for chaining)
  31329. */
  31330. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31331. if (mesh && mesh._masterMesh) {
  31332. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31333. return this;
  31334. }
  31335. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31336. this._LODLevels.push(level);
  31337. if (mesh) {
  31338. mesh._masterMesh = this;
  31339. }
  31340. this._sortLODLevels();
  31341. return this;
  31342. };
  31343. /**
  31344. * Returns the LOD level mesh at the passed distance or null if not found.
  31345. * It is related to the method `addLODLevel(distance, mesh)`.
  31346. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31347. * Returns an object Mesh or `null`.
  31348. */
  31349. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31350. for (var index = 0; index < this._LODLevels.length; index++) {
  31351. var level = this._LODLevels[index];
  31352. if (level.distance === distance) {
  31353. return level.mesh;
  31354. }
  31355. }
  31356. return null;
  31357. };
  31358. /**
  31359. * Remove a mesh from the LOD array
  31360. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31361. * @param {Mesh} mesh The mesh to be removed.
  31362. * @return {Mesh} This mesh (for chaining)
  31363. */
  31364. Mesh.prototype.removeLODLevel = function (mesh) {
  31365. for (var index = 0; index < this._LODLevels.length; index++) {
  31366. if (this._LODLevels[index].mesh === mesh) {
  31367. this._LODLevels.splice(index, 1);
  31368. if (mesh) {
  31369. mesh._masterMesh = null;
  31370. }
  31371. }
  31372. }
  31373. this._sortLODLevels();
  31374. return this;
  31375. };
  31376. /**
  31377. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31378. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31379. */
  31380. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31381. if (!this._LODLevels || this._LODLevels.length === 0) {
  31382. return this;
  31383. }
  31384. var bSphere;
  31385. if (boundingSphere) {
  31386. bSphere = boundingSphere;
  31387. }
  31388. else {
  31389. var boundingInfo = this.getBoundingInfo();
  31390. bSphere = boundingInfo.boundingSphere;
  31391. }
  31392. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31393. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31394. if (this.onLODLevelSelection) {
  31395. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31396. }
  31397. return this;
  31398. }
  31399. for (var index = 0; index < this._LODLevels.length; index++) {
  31400. var level = this._LODLevels[index];
  31401. if (level.distance < distanceToCamera) {
  31402. if (level.mesh) {
  31403. level.mesh._preActivate();
  31404. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31405. }
  31406. if (this.onLODLevelSelection) {
  31407. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31408. }
  31409. return level.mesh;
  31410. }
  31411. }
  31412. if (this.onLODLevelSelection) {
  31413. this.onLODLevelSelection(distanceToCamera, this, this);
  31414. }
  31415. return this;
  31416. };
  31417. Object.defineProperty(Mesh.prototype, "geometry", {
  31418. /**
  31419. * Returns the mesh internal Geometry object.
  31420. */
  31421. get: function () {
  31422. return this._geometry;
  31423. },
  31424. enumerable: true,
  31425. configurable: true
  31426. });
  31427. /**
  31428. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31429. */
  31430. Mesh.prototype.getTotalVertices = function () {
  31431. if (this._geometry === null || this._geometry === undefined) {
  31432. return 0;
  31433. }
  31434. return this._geometry.getTotalVertices();
  31435. };
  31436. /**
  31437. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31438. * 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.
  31439. * You can force the copy with forceCopy === true
  31440. * Returns null if the mesh has no geometry or no vertex buffer.
  31441. * Possible `kind` values :
  31442. * - BABYLON.VertexBuffer.PositionKind
  31443. * - BABYLON.VertexBuffer.UVKind
  31444. * - BABYLON.VertexBuffer.UV2Kind
  31445. * - BABYLON.VertexBuffer.UV3Kind
  31446. * - BABYLON.VertexBuffer.UV4Kind
  31447. * - BABYLON.VertexBuffer.UV5Kind
  31448. * - BABYLON.VertexBuffer.UV6Kind
  31449. * - BABYLON.VertexBuffer.ColorKind
  31450. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31451. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31452. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31453. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31454. */
  31455. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31456. if (!this._geometry) {
  31457. return null;
  31458. }
  31459. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31460. };
  31461. /**
  31462. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31463. * Returns `null` if the mesh has no geometry.
  31464. * Possible `kind` values :
  31465. * - BABYLON.VertexBuffer.PositionKind
  31466. * - BABYLON.VertexBuffer.UVKind
  31467. * - BABYLON.VertexBuffer.UV2Kind
  31468. * - BABYLON.VertexBuffer.UV3Kind
  31469. * - BABYLON.VertexBuffer.UV4Kind
  31470. * - BABYLON.VertexBuffer.UV5Kind
  31471. * - BABYLON.VertexBuffer.UV6Kind
  31472. * - BABYLON.VertexBuffer.ColorKind
  31473. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31474. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31475. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31476. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31477. */
  31478. Mesh.prototype.getVertexBuffer = function (kind) {
  31479. if (!this._geometry) {
  31480. return null;
  31481. }
  31482. return this._geometry.getVertexBuffer(kind);
  31483. };
  31484. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31485. if (!this._geometry) {
  31486. if (this._delayInfo) {
  31487. return this._delayInfo.indexOf(kind) !== -1;
  31488. }
  31489. return false;
  31490. }
  31491. return this._geometry.isVerticesDataPresent(kind);
  31492. };
  31493. /**
  31494. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31495. * Possible `kind` values :
  31496. * - BABYLON.VertexBuffer.PositionKind
  31497. * - BABYLON.VertexBuffer.UVKind
  31498. * - BABYLON.VertexBuffer.UV2Kind
  31499. * - BABYLON.VertexBuffer.UV3Kind
  31500. * - BABYLON.VertexBuffer.UV4Kind
  31501. * - BABYLON.VertexBuffer.UV5Kind
  31502. * - BABYLON.VertexBuffer.UV6Kind
  31503. * - BABYLON.VertexBuffer.ColorKind
  31504. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31505. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31506. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31507. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31508. */
  31509. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31510. if (!this._geometry) {
  31511. if (this._delayInfo) {
  31512. return this._delayInfo.indexOf(kind) !== -1;
  31513. }
  31514. return false;
  31515. }
  31516. return this._geometry.isVertexBufferUpdatable(kind);
  31517. };
  31518. /**
  31519. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31520. * Possible `kind` values :
  31521. * - BABYLON.VertexBuffer.PositionKind
  31522. * - BABYLON.VertexBuffer.UVKind
  31523. * - BABYLON.VertexBuffer.UV2Kind
  31524. * - BABYLON.VertexBuffer.UV3Kind
  31525. * - BABYLON.VertexBuffer.UV4Kind
  31526. * - BABYLON.VertexBuffer.UV5Kind
  31527. * - BABYLON.VertexBuffer.UV6Kind
  31528. * - BABYLON.VertexBuffer.ColorKind
  31529. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31530. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31531. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31532. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31533. */
  31534. Mesh.prototype.getVerticesDataKinds = function () {
  31535. if (!this._geometry) {
  31536. var result = new Array();
  31537. if (this._delayInfo) {
  31538. this._delayInfo.forEach(function (kind, index, array) {
  31539. result.push(kind);
  31540. });
  31541. }
  31542. return result;
  31543. }
  31544. return this._geometry.getVerticesDataKinds();
  31545. };
  31546. /**
  31547. * Returns a positive integer : the total number of indices in this mesh geometry.
  31548. * Returns zero if the mesh has no geometry.
  31549. */
  31550. Mesh.prototype.getTotalIndices = function () {
  31551. if (!this._geometry) {
  31552. return 0;
  31553. }
  31554. return this._geometry.getTotalIndices();
  31555. };
  31556. /**
  31557. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31558. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31559. * Returns an empty array if the mesh has no geometry.
  31560. */
  31561. Mesh.prototype.getIndices = function (copyWhenShared) {
  31562. if (!this._geometry) {
  31563. return [];
  31564. }
  31565. return this._geometry.getIndices(copyWhenShared);
  31566. };
  31567. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31568. get: function () {
  31569. return this._masterMesh !== null && this._masterMesh !== undefined;
  31570. },
  31571. enumerable: true,
  31572. configurable: true
  31573. });
  31574. /**
  31575. * Determine if the current mesh is ready to be rendered
  31576. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31577. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31578. * @returns true if all associated assets are ready (material, textures, shaders)
  31579. */
  31580. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31581. if (completeCheck === void 0) { completeCheck = false; }
  31582. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31583. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31584. return false;
  31585. }
  31586. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31587. return false;
  31588. }
  31589. if (!this.subMeshes || this.subMeshes.length === 0) {
  31590. return true;
  31591. }
  31592. if (!completeCheck) {
  31593. return true;
  31594. }
  31595. var engine = this.getEngine();
  31596. var scene = this.getScene();
  31597. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31598. this.computeWorldMatrix();
  31599. var mat = this.material || scene.defaultMaterial;
  31600. if (mat) {
  31601. if (mat.storeEffectOnSubMeshes) {
  31602. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31603. var subMesh = _a[_i];
  31604. var effectiveMaterial = subMesh.getMaterial();
  31605. if (effectiveMaterial) {
  31606. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31607. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31608. return false;
  31609. }
  31610. }
  31611. else {
  31612. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31613. return false;
  31614. }
  31615. }
  31616. }
  31617. }
  31618. }
  31619. else {
  31620. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31621. return false;
  31622. }
  31623. }
  31624. }
  31625. // Shadows
  31626. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31627. var light = _c[_b];
  31628. var generator = light.getShadowGenerator();
  31629. if (generator) {
  31630. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31631. var subMesh = _e[_d];
  31632. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31633. return false;
  31634. }
  31635. }
  31636. }
  31637. }
  31638. // LOD
  31639. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31640. var lod = _g[_f];
  31641. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31642. return false;
  31643. }
  31644. }
  31645. return true;
  31646. };
  31647. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31648. /**
  31649. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31650. * This property is pertinent only for updatable parametric shapes.
  31651. */
  31652. get: function () {
  31653. return this._areNormalsFrozen;
  31654. },
  31655. enumerable: true,
  31656. configurable: true
  31657. });
  31658. /**
  31659. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31660. * It has no effect at all on other shapes.
  31661. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31662. * Returns the Mesh.
  31663. */
  31664. Mesh.prototype.freezeNormals = function () {
  31665. this._areNormalsFrozen = true;
  31666. return this;
  31667. };
  31668. /**
  31669. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31670. * It has no effect at all on other shapes.
  31671. * It reactivates the mesh normals computation if it was previously frozen.
  31672. * Returns the Mesh.
  31673. */
  31674. Mesh.prototype.unfreezeNormals = function () {
  31675. this._areNormalsFrozen = false;
  31676. return this;
  31677. };
  31678. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31679. /**
  31680. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31681. */
  31682. set: function (count) {
  31683. this._overridenInstanceCount = count;
  31684. },
  31685. enumerable: true,
  31686. configurable: true
  31687. });
  31688. // Methods
  31689. /** @hidden */
  31690. Mesh.prototype._preActivate = function () {
  31691. var sceneRenderId = this.getScene().getRenderId();
  31692. if (this._preActivateId === sceneRenderId) {
  31693. return this;
  31694. }
  31695. this._preActivateId = sceneRenderId;
  31696. this._visibleInstances = null;
  31697. return this;
  31698. };
  31699. /** @hidden */
  31700. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31701. if (this._visibleInstances) {
  31702. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31703. }
  31704. return this;
  31705. };
  31706. /** @hidden */
  31707. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31708. if (!this._visibleInstances) {
  31709. this._visibleInstances = {};
  31710. this._visibleInstances.defaultRenderId = renderId;
  31711. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31712. }
  31713. if (!this._visibleInstances[renderId]) {
  31714. this._visibleInstances[renderId] = new Array();
  31715. }
  31716. this._visibleInstances[renderId].push(instance);
  31717. return this;
  31718. };
  31719. /**
  31720. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31721. * This means the mesh underlying bounding box and sphere are recomputed.
  31722. * Returns the Mesh.
  31723. */
  31724. Mesh.prototype.refreshBoundingInfo = function () {
  31725. return this._refreshBoundingInfo(false);
  31726. };
  31727. /** @hidden */
  31728. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31729. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31730. return this;
  31731. }
  31732. var data = this._getPositionData(applySkeleton);
  31733. if (data) {
  31734. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31735. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31736. }
  31737. if (this.subMeshes) {
  31738. for (var index = 0; index < this.subMeshes.length; index++) {
  31739. this.subMeshes[index].refreshBoundingInfo();
  31740. }
  31741. }
  31742. this._updateBoundingInfo();
  31743. return this;
  31744. };
  31745. Mesh.prototype._getPositionData = function (applySkeleton) {
  31746. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31747. if (data && applySkeleton && this.skeleton) {
  31748. data = BABYLON.Tools.Slice(data);
  31749. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31750. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31751. if (matricesWeightsData && matricesIndicesData) {
  31752. var needExtras = this.numBoneInfluencers > 4;
  31753. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31754. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31755. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31756. var tempVector = BABYLON.Tmp.Vector3[0];
  31757. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31758. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31759. var matWeightIdx = 0;
  31760. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31761. finalMatrix.reset();
  31762. var inf;
  31763. var weight;
  31764. for (inf = 0; inf < 4; inf++) {
  31765. weight = matricesWeightsData[matWeightIdx + inf];
  31766. if (weight > 0) {
  31767. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31768. finalMatrix.addToSelf(tempMatrix);
  31769. }
  31770. }
  31771. if (needExtras) {
  31772. for (inf = 0; inf < 4; inf++) {
  31773. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31774. if (weight > 0) {
  31775. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31776. finalMatrix.addToSelf(tempMatrix);
  31777. }
  31778. }
  31779. }
  31780. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31781. tempVector.toArray(data, index);
  31782. }
  31783. }
  31784. }
  31785. return data;
  31786. };
  31787. /** @hidden */
  31788. Mesh.prototype._createGlobalSubMesh = function (force) {
  31789. var totalVertices = this.getTotalVertices();
  31790. if (!totalVertices || !this.getIndices()) {
  31791. return null;
  31792. }
  31793. // Check if we need to recreate the submeshes
  31794. if (this.subMeshes && this.subMeshes.length > 0) {
  31795. var ib = this.getIndices();
  31796. if (!ib) {
  31797. return null;
  31798. }
  31799. var totalIndices = ib.length;
  31800. var needToRecreate = false;
  31801. if (force) {
  31802. needToRecreate = true;
  31803. }
  31804. else {
  31805. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31806. var submesh = _a[_i];
  31807. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31808. needToRecreate = true;
  31809. break;
  31810. }
  31811. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31812. needToRecreate = true;
  31813. break;
  31814. }
  31815. }
  31816. }
  31817. if (!needToRecreate) {
  31818. return this.subMeshes[0];
  31819. }
  31820. }
  31821. this.releaseSubMeshes();
  31822. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31823. };
  31824. Mesh.prototype.subdivide = function (count) {
  31825. if (count < 1) {
  31826. return;
  31827. }
  31828. var totalIndices = this.getTotalIndices();
  31829. var subdivisionSize = (totalIndices / count) | 0;
  31830. var offset = 0;
  31831. // Ensure that subdivisionSize is a multiple of 3
  31832. while (subdivisionSize % 3 !== 0) {
  31833. subdivisionSize++;
  31834. }
  31835. this.releaseSubMeshes();
  31836. for (var index = 0; index < count; index++) {
  31837. if (offset >= totalIndices) {
  31838. break;
  31839. }
  31840. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31841. offset += subdivisionSize;
  31842. }
  31843. this.synchronizeInstances();
  31844. };
  31845. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31846. if (updatable === void 0) { updatable = false; }
  31847. if (!this._geometry) {
  31848. var vertexData = new BABYLON.VertexData();
  31849. vertexData.set(data, kind);
  31850. var scene = this.getScene();
  31851. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31852. }
  31853. else {
  31854. this._geometry.setVerticesData(kind, data, updatable, stride);
  31855. }
  31856. return this;
  31857. };
  31858. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31859. if (updatable === void 0) { updatable = true; }
  31860. var vb = this.getVertexBuffer(kind);
  31861. if (!vb || vb.isUpdatable() === updatable) {
  31862. return;
  31863. }
  31864. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31865. };
  31866. /**
  31867. * Sets the mesh VertexBuffer.
  31868. * Returns the Mesh.
  31869. */
  31870. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31871. if (!this._geometry) {
  31872. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31873. }
  31874. this._geometry.setVerticesBuffer(buffer);
  31875. return this;
  31876. };
  31877. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31878. if (!this._geometry) {
  31879. return this;
  31880. }
  31881. if (!makeItUnique) {
  31882. this._geometry.updateVerticesData(kind, data, updateExtends);
  31883. }
  31884. else {
  31885. this.makeGeometryUnique();
  31886. this.updateVerticesData(kind, data, updateExtends, false);
  31887. }
  31888. return this;
  31889. };
  31890. /**
  31891. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31892. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31893. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31894. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31895. * Returns the Mesh.
  31896. */
  31897. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31898. if (computeNormals === void 0) { computeNormals = true; }
  31899. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31900. if (!positions) {
  31901. return this;
  31902. }
  31903. positionFunction(positions);
  31904. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31905. if (computeNormals) {
  31906. var indices = this.getIndices();
  31907. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31908. if (!normals) {
  31909. return this;
  31910. }
  31911. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31912. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31913. }
  31914. return this;
  31915. };
  31916. /**
  31917. * Creates a un-shared specific occurence of the geometry for the mesh.
  31918. * Returns the Mesh.
  31919. */
  31920. Mesh.prototype.makeGeometryUnique = function () {
  31921. if (!this._geometry) {
  31922. return this;
  31923. }
  31924. var oldGeometry = this._geometry;
  31925. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31926. oldGeometry.releaseForMesh(this, true);
  31927. geometry.applyToMesh(this);
  31928. return this;
  31929. };
  31930. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31931. if (totalVertices === void 0) { totalVertices = null; }
  31932. if (updatable === void 0) { updatable = false; }
  31933. if (!this._geometry) {
  31934. var vertexData = new BABYLON.VertexData();
  31935. vertexData.indices = indices;
  31936. var scene = this.getScene();
  31937. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31938. }
  31939. else {
  31940. this._geometry.setIndices(indices, totalVertices, updatable);
  31941. }
  31942. return this;
  31943. };
  31944. /**
  31945. * Update the current index buffer
  31946. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31947. * Returns the Mesh.
  31948. */
  31949. Mesh.prototype.updateIndices = function (indices, offset) {
  31950. if (!this._geometry) {
  31951. return this;
  31952. }
  31953. this._geometry.updateIndices(indices, offset);
  31954. return this;
  31955. };
  31956. /**
  31957. * Invert the geometry to move from a right handed system to a left handed one.
  31958. * Returns the Mesh.
  31959. */
  31960. Mesh.prototype.toLeftHanded = function () {
  31961. if (!this._geometry) {
  31962. return this;
  31963. }
  31964. this._geometry.toLeftHanded();
  31965. return this;
  31966. };
  31967. /** @hidden */
  31968. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31969. if (!this._geometry) {
  31970. return this;
  31971. }
  31972. var engine = this.getScene().getEngine();
  31973. // Wireframe
  31974. var indexToBind;
  31975. if (this._unIndexed) {
  31976. indexToBind = null;
  31977. }
  31978. else {
  31979. switch (fillMode) {
  31980. case BABYLON.Material.PointFillMode:
  31981. indexToBind = null;
  31982. break;
  31983. case BABYLON.Material.WireFrameFillMode:
  31984. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31985. break;
  31986. default:
  31987. case BABYLON.Material.TriangleFillMode:
  31988. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31989. break;
  31990. }
  31991. }
  31992. // VBOs
  31993. this._geometry._bind(effect, indexToBind);
  31994. return this;
  31995. };
  31996. /** @hidden */
  31997. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31998. if (alternate === void 0) { alternate = false; }
  31999. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32000. return this;
  32001. }
  32002. if (this._onBeforeDrawObservable) {
  32003. this._onBeforeDrawObservable.notifyObservers(this);
  32004. }
  32005. var scene = this.getScene();
  32006. var engine = scene.getEngine();
  32007. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32008. // or triangles as points
  32009. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32010. }
  32011. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32012. // Triangles as wireframe
  32013. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32014. }
  32015. else {
  32016. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32017. }
  32018. if (scene._isAlternateRenderingEnabled && !alternate) {
  32019. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32020. if (!effect || !scene.activeCamera) {
  32021. return this;
  32022. }
  32023. scene._switchToAlternateCameraConfiguration(true);
  32024. this._effectiveMaterial.bindView(effect);
  32025. this._effectiveMaterial.bindViewProjection(effect);
  32026. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32027. this._draw(subMesh, fillMode, instancesCount, true);
  32028. engine.setViewport(scene.activeCamera.viewport);
  32029. scene._switchToAlternateCameraConfiguration(false);
  32030. this._effectiveMaterial.bindView(effect);
  32031. this._effectiveMaterial.bindViewProjection(effect);
  32032. }
  32033. return this;
  32034. };
  32035. /**
  32036. * Registers for this mesh a javascript function called just before the rendering process.
  32037. * This function is passed the current mesh.
  32038. * Return the Mesh.
  32039. */
  32040. Mesh.prototype.registerBeforeRender = function (func) {
  32041. this.onBeforeRenderObservable.add(func);
  32042. return this;
  32043. };
  32044. /**
  32045. * Disposes a previously registered javascript function called before the rendering.
  32046. * This function is passed the current mesh.
  32047. * Returns the Mesh.
  32048. */
  32049. Mesh.prototype.unregisterBeforeRender = function (func) {
  32050. this.onBeforeRenderObservable.removeCallback(func);
  32051. return this;
  32052. };
  32053. /**
  32054. * Registers for this mesh a javascript function called just after the rendering is complete.
  32055. * This function is passed the current mesh.
  32056. * Returns the Mesh.
  32057. */
  32058. Mesh.prototype.registerAfterRender = function (func) {
  32059. this.onAfterRenderObservable.add(func);
  32060. return this;
  32061. };
  32062. /**
  32063. * Disposes a previously registered javascript function called after the rendering.
  32064. * This function is passed the current mesh.
  32065. * Return the Mesh.
  32066. */
  32067. Mesh.prototype.unregisterAfterRender = function (func) {
  32068. this.onAfterRenderObservable.removeCallback(func);
  32069. return this;
  32070. };
  32071. /** @hidden */
  32072. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32073. var scene = this.getScene();
  32074. this._batchCache.mustReturn = false;
  32075. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32076. this._batchCache.visibleInstances[subMeshId] = null;
  32077. if (this._visibleInstances) {
  32078. var currentRenderId = scene.getRenderId();
  32079. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32080. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32081. var selfRenderId = this._renderId;
  32082. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32083. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32084. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32085. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32086. }
  32087. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32088. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32089. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32090. this._batchCache.mustReturn = true;
  32091. return this._batchCache;
  32092. }
  32093. if (currentRenderId !== selfRenderId) {
  32094. this._batchCache.renderSelf[subMeshId] = false;
  32095. }
  32096. }
  32097. this._renderIdForInstances[subMeshId] = currentRenderId;
  32098. }
  32099. return this._batchCache;
  32100. };
  32101. /** @hidden */
  32102. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32103. var visibleInstances = batch.visibleInstances[subMesh._id];
  32104. if (!visibleInstances) {
  32105. return this;
  32106. }
  32107. var matricesCount = visibleInstances.length + 1;
  32108. var bufferSize = matricesCount * 16 * 4;
  32109. var currentInstancesBufferSize = this._instancesBufferSize;
  32110. var instancesBuffer = this._instancesBuffer;
  32111. while (this._instancesBufferSize < bufferSize) {
  32112. this._instancesBufferSize *= 2;
  32113. }
  32114. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32115. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32116. }
  32117. var offset = 0;
  32118. var instancesCount = 0;
  32119. var world = this.getWorldMatrix();
  32120. if (batch.renderSelf[subMesh._id]) {
  32121. world.copyToArray(this._instancesData, offset);
  32122. offset += 16;
  32123. instancesCount++;
  32124. }
  32125. if (visibleInstances) {
  32126. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32127. var instance = visibleInstances[instanceIndex];
  32128. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32129. offset += 16;
  32130. instancesCount++;
  32131. }
  32132. }
  32133. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32134. if (instancesBuffer) {
  32135. instancesBuffer.dispose();
  32136. }
  32137. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32138. this._instancesBuffer = instancesBuffer;
  32139. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32140. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32141. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32142. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32143. }
  32144. else {
  32145. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32146. }
  32147. this._bind(subMesh, effect, fillMode);
  32148. this._draw(subMesh, fillMode, instancesCount);
  32149. engine.unbindInstanceAttributes();
  32150. return this;
  32151. };
  32152. /** @hidden */
  32153. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32154. var scene = this.getScene();
  32155. var engine = scene.getEngine();
  32156. if (hardwareInstancedRendering) {
  32157. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32158. }
  32159. else {
  32160. if (batch.renderSelf[subMesh._id]) {
  32161. // Draw
  32162. if (onBeforeDraw) {
  32163. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32164. }
  32165. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32166. }
  32167. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32168. if (visibleInstancesForSubMesh) {
  32169. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32170. var instance = visibleInstancesForSubMesh[instanceIndex];
  32171. // World
  32172. var world = instance.getWorldMatrix();
  32173. if (onBeforeDraw) {
  32174. onBeforeDraw(true, world, effectiveMaterial);
  32175. }
  32176. // Draw
  32177. this._draw(subMesh, fillMode);
  32178. }
  32179. }
  32180. }
  32181. return this;
  32182. };
  32183. /**
  32184. * 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
  32185. * @param subMesh defines the subMesh to render
  32186. * @param enableAlphaMode defines if alpha mode can be changed
  32187. * @returns the current mesh
  32188. */
  32189. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32190. this._checkOcclusionQuery();
  32191. if (this._isOccluded) {
  32192. return this;
  32193. }
  32194. var scene = this.getScene();
  32195. // Managing instances
  32196. var batch = this._getInstancesRenderList(subMesh._id);
  32197. if (batch.mustReturn) {
  32198. return this;
  32199. }
  32200. // Checking geometry state
  32201. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32202. return this;
  32203. }
  32204. if (this._onBeforeRenderObservable) {
  32205. this._onBeforeRenderObservable.notifyObservers(this);
  32206. }
  32207. var engine = scene.getEngine();
  32208. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32209. // Material
  32210. var material = subMesh.getMaterial();
  32211. if (!material) {
  32212. return this;
  32213. }
  32214. this._effectiveMaterial = material;
  32215. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32216. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32217. return this;
  32218. }
  32219. }
  32220. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32221. return this;
  32222. }
  32223. // Alpha mode
  32224. if (enableAlphaMode) {
  32225. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32226. }
  32227. // Outline - step 1
  32228. var savedDepthWrite = engine.getDepthWrite();
  32229. if (this.renderOutline) {
  32230. engine.setDepthWrite(false);
  32231. scene.getOutlineRenderer().render(subMesh, batch);
  32232. engine.setDepthWrite(savedDepthWrite);
  32233. }
  32234. var effect;
  32235. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32236. effect = subMesh.effect;
  32237. }
  32238. else {
  32239. effect = this._effectiveMaterial.getEffect();
  32240. }
  32241. if (!effect) {
  32242. return this;
  32243. }
  32244. var sideOrientation = this.overrideMaterialSideOrientation;
  32245. if (sideOrientation == null) {
  32246. sideOrientation = this._effectiveMaterial.sideOrientation;
  32247. if (this._getWorldMatrixDeterminant() < 0) {
  32248. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32249. }
  32250. }
  32251. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32252. if (this._effectiveMaterial.forceDepthWrite) {
  32253. engine.setDepthWrite(true);
  32254. }
  32255. // Bind
  32256. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32257. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32258. this._bind(subMesh, effect, fillMode);
  32259. }
  32260. var world = this.getWorldMatrix();
  32261. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32262. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32263. }
  32264. else {
  32265. this._effectiveMaterial.bind(world, this);
  32266. }
  32267. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32268. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32269. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32270. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32271. }
  32272. // Draw
  32273. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32274. // Unbind
  32275. this._effectiveMaterial.unbind();
  32276. // Outline - step 2
  32277. if (this.renderOutline && savedDepthWrite) {
  32278. engine.setDepthWrite(true);
  32279. engine.setColorWrite(false);
  32280. scene.getOutlineRenderer().render(subMesh, batch);
  32281. engine.setColorWrite(true);
  32282. }
  32283. // Overlay
  32284. if (this.renderOverlay) {
  32285. var currentMode = engine.getAlphaMode();
  32286. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32287. scene.getOutlineRenderer().render(subMesh, batch, true);
  32288. engine.setAlphaMode(currentMode);
  32289. }
  32290. if (this._onAfterRenderObservable) {
  32291. this._onAfterRenderObservable.notifyObservers(this);
  32292. }
  32293. return this;
  32294. };
  32295. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32296. if (isInstance && effectiveMaterial) {
  32297. effectiveMaterial.bindOnlyWorldMatrix(world);
  32298. }
  32299. };
  32300. /**
  32301. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32302. */
  32303. Mesh.prototype.getEmittedParticleSystems = function () {
  32304. var results = new Array();
  32305. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32306. var particleSystem = this.getScene().particleSystems[index];
  32307. if (particleSystem.emitter === this) {
  32308. results.push(particleSystem);
  32309. }
  32310. }
  32311. return results;
  32312. };
  32313. /**
  32314. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32315. */
  32316. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32317. var results = new Array();
  32318. var descendants = this.getDescendants();
  32319. descendants.push(this);
  32320. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32321. var particleSystem = this.getScene().particleSystems[index];
  32322. var emitter = particleSystem.emitter;
  32323. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32324. results.push(particleSystem);
  32325. }
  32326. }
  32327. return results;
  32328. };
  32329. /**
  32330. * Normalize matrix weights so that all vertices have a total weight set to 1
  32331. */
  32332. Mesh.prototype.cleanMatrixWeights = function () {
  32333. var epsilon = 1e-3;
  32334. var noInfluenceBoneIndex = 0.0;
  32335. if (this.skeleton) {
  32336. noInfluenceBoneIndex = this.skeleton.bones.length;
  32337. }
  32338. else {
  32339. return;
  32340. }
  32341. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32342. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32343. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32344. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32345. var influencers = this.numBoneInfluencers;
  32346. var size = matricesWeights.length;
  32347. for (var i = 0; i < size; i += 4) {
  32348. var weight = 0.0;
  32349. var firstZeroWeight = -1;
  32350. for (var j = 0; j < 4; j++) {
  32351. var w = matricesWeights[i + j];
  32352. weight += w;
  32353. if (w < epsilon && firstZeroWeight < 0) {
  32354. firstZeroWeight = j;
  32355. }
  32356. }
  32357. if (matricesWeightsExtra) {
  32358. for (var j = 0; j < 4; j++) {
  32359. var w = matricesWeightsExtra[i + j];
  32360. weight += w;
  32361. if (w < epsilon && firstZeroWeight < 0) {
  32362. firstZeroWeight = j + 4;
  32363. }
  32364. }
  32365. }
  32366. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32367. firstZeroWeight = influencers - 1;
  32368. }
  32369. if (weight > epsilon) {
  32370. var mweight = 1.0 / weight;
  32371. for (var j = 0; j < 4; j++) {
  32372. matricesWeights[i + j] *= mweight;
  32373. }
  32374. if (matricesWeightsExtra) {
  32375. for (var j = 0; j < 4; j++) {
  32376. matricesWeightsExtra[i + j] *= mweight;
  32377. }
  32378. }
  32379. }
  32380. else {
  32381. if (firstZeroWeight >= 4) {
  32382. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32383. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32384. }
  32385. else {
  32386. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32387. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32388. }
  32389. }
  32390. }
  32391. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32392. if (matricesIndicesExtra) {
  32393. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32394. }
  32395. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32396. if (matricesWeightsExtra) {
  32397. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32398. }
  32399. };
  32400. /** @hidden */
  32401. Mesh.prototype._checkDelayState = function () {
  32402. var scene = this.getScene();
  32403. if (this._geometry) {
  32404. this._geometry.load(scene);
  32405. }
  32406. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32407. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32408. this._queueLoad(scene);
  32409. }
  32410. return this;
  32411. };
  32412. Mesh.prototype._queueLoad = function (scene) {
  32413. var _this = this;
  32414. scene._addPendingData(this);
  32415. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32416. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32417. if (data instanceof ArrayBuffer) {
  32418. _this._delayLoadingFunction(data, _this);
  32419. }
  32420. else {
  32421. _this._delayLoadingFunction(JSON.parse(data), _this);
  32422. }
  32423. _this.instances.forEach(function (instance) {
  32424. instance._syncSubMeshes();
  32425. });
  32426. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32427. scene._removePendingData(_this);
  32428. }, function () { }, scene.database, getBinaryData);
  32429. return this;
  32430. };
  32431. /**
  32432. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32433. */
  32434. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32435. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32436. return false;
  32437. }
  32438. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32439. return false;
  32440. }
  32441. this._checkDelayState();
  32442. return true;
  32443. };
  32444. /**
  32445. * Sets the mesh material by the material or multiMaterial `id` property.
  32446. * The material `id` is a string identifying the material or the multiMaterial.
  32447. * This method returns the Mesh.
  32448. */
  32449. Mesh.prototype.setMaterialByID = function (id) {
  32450. var materials = this.getScene().materials;
  32451. var index;
  32452. for (index = materials.length - 1; index > -1; index--) {
  32453. if (materials[index].id === id) {
  32454. this.material = materials[index];
  32455. return this;
  32456. }
  32457. }
  32458. // Multi
  32459. var multiMaterials = this.getScene().multiMaterials;
  32460. for (index = multiMaterials.length - 1; index > -1; index--) {
  32461. if (multiMaterials[index].id === id) {
  32462. this.material = multiMaterials[index];
  32463. return this;
  32464. }
  32465. }
  32466. return this;
  32467. };
  32468. /**
  32469. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32470. */
  32471. Mesh.prototype.getAnimatables = function () {
  32472. var results = new Array();
  32473. if (this.material) {
  32474. results.push(this.material);
  32475. }
  32476. if (this.skeleton) {
  32477. results.push(this.skeleton);
  32478. }
  32479. return results;
  32480. };
  32481. /**
  32482. * Modifies the mesh geometry according to the passed transformation matrix.
  32483. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32484. * The mesh normals are modified accordingly the same transformation.
  32485. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32486. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32487. * Returns the Mesh.
  32488. */
  32489. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32490. // Position
  32491. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32492. return this;
  32493. }
  32494. var submeshes = this.subMeshes.splice(0);
  32495. this._resetPointsArrayCache();
  32496. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32497. var temp = new Array();
  32498. var index;
  32499. for (index = 0; index < data.length; index += 3) {
  32500. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32501. }
  32502. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32503. // Normals
  32504. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32505. return this;
  32506. }
  32507. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32508. temp = [];
  32509. for (index = 0; index < data.length; index += 3) {
  32510. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32511. }
  32512. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32513. // flip faces?
  32514. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32515. this.flipFaces();
  32516. }
  32517. // Restore submeshes
  32518. this.releaseSubMeshes();
  32519. this.subMeshes = submeshes;
  32520. return this;
  32521. };
  32522. /**
  32523. * Modifies the mesh geometry according to its own current World Matrix.
  32524. * The mesh World Matrix is then reset.
  32525. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32526. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32527. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32528. * Returns the Mesh.
  32529. */
  32530. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32531. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32532. this.scaling.copyFromFloats(1, 1, 1);
  32533. this.position.copyFromFloats(0, 0, 0);
  32534. this.rotation.copyFromFloats(0, 0, 0);
  32535. //only if quaternion is already set
  32536. if (this.rotationQuaternion) {
  32537. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32538. }
  32539. this._worldMatrix = BABYLON.Matrix.Identity();
  32540. return this;
  32541. };
  32542. Object.defineProperty(Mesh.prototype, "_positions", {
  32543. // Cache
  32544. get: function () {
  32545. if (this._geometry) {
  32546. return this._geometry._positions;
  32547. }
  32548. return null;
  32549. },
  32550. enumerable: true,
  32551. configurable: true
  32552. });
  32553. /** @hidden */
  32554. Mesh.prototype._resetPointsArrayCache = function () {
  32555. if (this._geometry) {
  32556. this._geometry._resetPointsArrayCache();
  32557. }
  32558. return this;
  32559. };
  32560. /** @hidden */
  32561. Mesh.prototype._generatePointsArray = function () {
  32562. if (this._geometry) {
  32563. return this._geometry._generatePointsArray();
  32564. }
  32565. return false;
  32566. };
  32567. /**
  32568. * Returns a new Mesh object generated from the current mesh properties.
  32569. * This method must not get confused with createInstance().
  32570. * The parameter `name` is a string, the name given to the new mesh.
  32571. * The optional parameter `newParent` can be any Node object (default `null`).
  32572. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32573. * 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.
  32574. */
  32575. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32576. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32577. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32578. };
  32579. /**
  32580. * Releases resources associated with this mesh.
  32581. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32582. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32583. */
  32584. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32585. var _this = this;
  32586. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32587. this.morphTargetManager = null;
  32588. if (this._geometry) {
  32589. this._geometry.releaseForMesh(this, true);
  32590. }
  32591. if (this._onBeforeDrawObservable) {
  32592. this._onBeforeDrawObservable.clear();
  32593. }
  32594. if (this._onBeforeRenderObservable) {
  32595. this._onBeforeRenderObservable.clear();
  32596. }
  32597. if (this._onAfterRenderObservable) {
  32598. this._onAfterRenderObservable.clear();
  32599. }
  32600. // Sources
  32601. var meshes = this.getScene().meshes;
  32602. meshes.forEach(function (abstractMesh) {
  32603. var mesh = abstractMesh;
  32604. if (mesh._source && mesh._source === _this) {
  32605. mesh._source = null;
  32606. }
  32607. });
  32608. this._source = null;
  32609. // Instances
  32610. if (this._instancesBuffer) {
  32611. this._instancesBuffer.dispose();
  32612. this._instancesBuffer = null;
  32613. }
  32614. while (this.instances.length) {
  32615. this.instances[0].dispose();
  32616. }
  32617. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32618. };
  32619. /**
  32620. * Modifies the mesh geometry according to a displacement map.
  32621. * 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.
  32622. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32623. * This method returns nothing.
  32624. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32625. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32626. * 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.
  32627. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32628. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32629. *
  32630. * Returns the Mesh.
  32631. */
  32632. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32633. var _this = this;
  32634. var scene = this.getScene();
  32635. var onload = function (img) {
  32636. // Getting height map data
  32637. var canvas = document.createElement("canvas");
  32638. var context = canvas.getContext("2d");
  32639. var heightMapWidth = img.width;
  32640. var heightMapHeight = img.height;
  32641. canvas.width = heightMapWidth;
  32642. canvas.height = heightMapHeight;
  32643. context.drawImage(img, 0, 0);
  32644. // Create VertexData from map data
  32645. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32646. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32647. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32648. //execute success callback, if set
  32649. if (onSuccess) {
  32650. onSuccess(_this);
  32651. }
  32652. };
  32653. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32654. return this;
  32655. };
  32656. /**
  32657. * Modifies the mesh geometry according to a displacementMap buffer.
  32658. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  32659. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32660. * This method returns nothing.
  32661. * 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.
  32662. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32663. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32664. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32665. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32666. *
  32667. * Returns the Mesh.
  32668. */
  32669. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32670. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32671. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32672. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32673. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32674. return this;
  32675. }
  32676. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32677. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32678. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32679. var position = BABYLON.Vector3.Zero();
  32680. var normal = BABYLON.Vector3.Zero();
  32681. var uv = BABYLON.Vector2.Zero();
  32682. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32683. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32684. for (var index = 0; index < positions.length; index += 3) {
  32685. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32686. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32687. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32688. // Compute height
  32689. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32690. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32691. var pos = (u + v * heightMapWidth) * 4;
  32692. var r = buffer[pos] / 255.0;
  32693. var g = buffer[pos + 1] / 255.0;
  32694. var b = buffer[pos + 2] / 255.0;
  32695. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32696. normal.normalize();
  32697. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32698. position = position.add(normal);
  32699. position.toArray(positions, index);
  32700. }
  32701. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32702. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32703. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32704. return this;
  32705. };
  32706. /**
  32707. * Modify the mesh to get a flat shading rendering.
  32708. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32709. * This method returns the Mesh.
  32710. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32711. */
  32712. Mesh.prototype.convertToFlatShadedMesh = function () {
  32713. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32714. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32715. var kinds = this.getVerticesDataKinds();
  32716. var vbs = {};
  32717. var data = {};
  32718. var newdata = {};
  32719. var updatableNormals = false;
  32720. var kindIndex;
  32721. var kind;
  32722. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32723. kind = kinds[kindIndex];
  32724. var vertexBuffer = this.getVertexBuffer(kind);
  32725. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32726. updatableNormals = vertexBuffer.isUpdatable();
  32727. kinds.splice(kindIndex, 1);
  32728. kindIndex--;
  32729. continue;
  32730. }
  32731. vbs[kind] = vertexBuffer;
  32732. data[kind] = vbs[kind].getData();
  32733. newdata[kind] = [];
  32734. }
  32735. // Save previous submeshes
  32736. var previousSubmeshes = this.subMeshes.slice(0);
  32737. var indices = this.getIndices();
  32738. var totalIndices = this.getTotalIndices();
  32739. // Generating unique vertices per face
  32740. var index;
  32741. for (index = 0; index < totalIndices; index++) {
  32742. var vertexIndex = indices[index];
  32743. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32744. kind = kinds[kindIndex];
  32745. var stride = vbs[kind].getStrideSize();
  32746. for (var offset = 0; offset < stride; offset++) {
  32747. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32748. }
  32749. }
  32750. }
  32751. // Updating faces & normal
  32752. var normals = [];
  32753. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32754. for (index = 0; index < totalIndices; index += 3) {
  32755. indices[index] = index;
  32756. indices[index + 1] = index + 1;
  32757. indices[index + 2] = index + 2;
  32758. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32759. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32760. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32761. var p1p2 = p1.subtract(p2);
  32762. var p3p2 = p3.subtract(p2);
  32763. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32764. // Store same normals for every vertex
  32765. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32766. normals.push(normal.x);
  32767. normals.push(normal.y);
  32768. normals.push(normal.z);
  32769. }
  32770. }
  32771. this.setIndices(indices);
  32772. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32773. // Updating vertex buffers
  32774. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32775. kind = kinds[kindIndex];
  32776. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32777. }
  32778. // Updating submeshes
  32779. this.releaseSubMeshes();
  32780. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32781. var previousOne = previousSubmeshes[submeshIndex];
  32782. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32783. }
  32784. this.synchronizeInstances();
  32785. return this;
  32786. };
  32787. /**
  32788. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32789. * In other words, more vertices, no more indices and a single bigger VBO.
  32790. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32791. * Returns the Mesh.
  32792. */
  32793. Mesh.prototype.convertToUnIndexedMesh = function () {
  32794. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32795. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32796. var kinds = this.getVerticesDataKinds();
  32797. var vbs = {};
  32798. var data = {};
  32799. var newdata = {};
  32800. var kindIndex;
  32801. var kind;
  32802. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32803. kind = kinds[kindIndex];
  32804. var vertexBuffer = this.getVertexBuffer(kind);
  32805. vbs[kind] = vertexBuffer;
  32806. data[kind] = vbs[kind].getData();
  32807. newdata[kind] = [];
  32808. }
  32809. // Save previous submeshes
  32810. var previousSubmeshes = this.subMeshes.slice(0);
  32811. var indices = this.getIndices();
  32812. var totalIndices = this.getTotalIndices();
  32813. // Generating unique vertices per face
  32814. var index;
  32815. for (index = 0; index < totalIndices; index++) {
  32816. var vertexIndex = indices[index];
  32817. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32818. kind = kinds[kindIndex];
  32819. var stride = vbs[kind].getStrideSize();
  32820. for (var offset = 0; offset < stride; offset++) {
  32821. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32822. }
  32823. }
  32824. }
  32825. // Updating indices
  32826. for (index = 0; index < totalIndices; index += 3) {
  32827. indices[index] = index;
  32828. indices[index + 1] = index + 1;
  32829. indices[index + 2] = index + 2;
  32830. }
  32831. this.setIndices(indices);
  32832. // Updating vertex buffers
  32833. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32834. kind = kinds[kindIndex];
  32835. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32836. }
  32837. // Updating submeshes
  32838. this.releaseSubMeshes();
  32839. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32840. var previousOne = previousSubmeshes[submeshIndex];
  32841. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32842. }
  32843. this._unIndexed = true;
  32844. this.synchronizeInstances();
  32845. return this;
  32846. };
  32847. /**
  32848. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32849. * This method returns the Mesh.
  32850. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32851. */
  32852. Mesh.prototype.flipFaces = function (flipNormals) {
  32853. if (flipNormals === void 0) { flipNormals = false; }
  32854. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32855. var i;
  32856. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32857. for (i = 0; i < vertex_data.normals.length; i++) {
  32858. vertex_data.normals[i] *= -1;
  32859. }
  32860. }
  32861. if (vertex_data.indices) {
  32862. var temp;
  32863. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32864. // reassign indices
  32865. temp = vertex_data.indices[i + 1];
  32866. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32867. vertex_data.indices[i + 2] = temp;
  32868. }
  32869. }
  32870. vertex_data.applyToMesh(this);
  32871. return this;
  32872. };
  32873. // Instances
  32874. /**
  32875. * Creates a new InstancedMesh object from the mesh model.
  32876. * An instance shares the same properties and the same material than its model.
  32877. * Only these properties of each instance can then be set individually :
  32878. * - position
  32879. * - rotation
  32880. * - rotationQuaternion
  32881. * - setPivotMatrix
  32882. * - scaling
  32883. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32884. * Warning : this method is not supported for Line mesh and LineSystem
  32885. */
  32886. Mesh.prototype.createInstance = function (name) {
  32887. return new BABYLON.InstancedMesh(name, this);
  32888. };
  32889. /**
  32890. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32891. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32892. * This method returns the Mesh.
  32893. */
  32894. Mesh.prototype.synchronizeInstances = function () {
  32895. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32896. var instance = this.instances[instanceIndex];
  32897. instance._syncSubMeshes();
  32898. }
  32899. return this;
  32900. };
  32901. /**
  32902. * Simplify the mesh according to the given array of settings.
  32903. * Function will return immediately and will simplify async. It returns the Mesh.
  32904. * @param settings a collection of simplification settings.
  32905. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32906. * @param type the type of simplification to run.
  32907. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32908. */
  32909. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32910. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32911. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32912. this.getScene().simplificationQueue.addTask({
  32913. settings: settings,
  32914. parallelProcessing: parallelProcessing,
  32915. mesh: this,
  32916. simplificationType: simplificationType,
  32917. successCallback: successCallback
  32918. });
  32919. return this;
  32920. };
  32921. /**
  32922. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32923. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32924. * This should be used together with the simplification to avoid disappearing triangles.
  32925. * Returns the Mesh.
  32926. * @param successCallback an optional success callback to be called after the optimization finished.
  32927. */
  32928. Mesh.prototype.optimizeIndices = function (successCallback) {
  32929. var _this = this;
  32930. var indices = this.getIndices();
  32931. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32932. if (!positions || !indices) {
  32933. return this;
  32934. }
  32935. var vectorPositions = new Array();
  32936. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32937. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32938. }
  32939. var dupes = new Array();
  32940. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32941. var realPos = vectorPositions.length - 1 - iteration;
  32942. var testedPosition = vectorPositions[realPos];
  32943. for (var j = 0; j < realPos; ++j) {
  32944. var againstPosition = vectorPositions[j];
  32945. if (testedPosition.equals(againstPosition)) {
  32946. dupes[realPos] = j;
  32947. break;
  32948. }
  32949. }
  32950. }, function () {
  32951. for (var i = 0; i < indices.length; ++i) {
  32952. indices[i] = dupes[indices[i]] || indices[i];
  32953. }
  32954. //indices are now reordered
  32955. var originalSubMeshes = _this.subMeshes.slice(0);
  32956. _this.setIndices(indices);
  32957. _this.subMeshes = originalSubMeshes;
  32958. if (successCallback) {
  32959. successCallback(_this);
  32960. }
  32961. });
  32962. return this;
  32963. };
  32964. Mesh.prototype.serialize = function (serializationObject) {
  32965. serializationObject.name = this.name;
  32966. serializationObject.id = this.id;
  32967. serializationObject.type = this.getClassName();
  32968. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32969. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32970. }
  32971. serializationObject.position = this.position.asArray();
  32972. if (this.rotationQuaternion) {
  32973. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32974. }
  32975. else if (this.rotation) {
  32976. serializationObject.rotation = this.rotation.asArray();
  32977. }
  32978. serializationObject.scaling = this.scaling.asArray();
  32979. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32980. serializationObject.isEnabled = this.isEnabled(false);
  32981. serializationObject.isVisible = this.isVisible;
  32982. serializationObject.infiniteDistance = this.infiniteDistance;
  32983. serializationObject.pickable = this.isPickable;
  32984. serializationObject.receiveShadows = this.receiveShadows;
  32985. serializationObject.billboardMode = this.billboardMode;
  32986. serializationObject.visibility = this.visibility;
  32987. serializationObject.checkCollisions = this.checkCollisions;
  32988. serializationObject.isBlocker = this.isBlocker;
  32989. // Parent
  32990. if (this.parent) {
  32991. serializationObject.parentId = this.parent.id;
  32992. }
  32993. // Geometry
  32994. serializationObject.isUnIndexed = this.isUnIndexed;
  32995. var geometry = this._geometry;
  32996. if (geometry) {
  32997. var geometryId = geometry.id;
  32998. serializationObject.geometryId = geometryId;
  32999. // SubMeshes
  33000. serializationObject.subMeshes = [];
  33001. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33002. var subMesh = this.subMeshes[subIndex];
  33003. serializationObject.subMeshes.push({
  33004. materialIndex: subMesh.materialIndex,
  33005. verticesStart: subMesh.verticesStart,
  33006. verticesCount: subMesh.verticesCount,
  33007. indexStart: subMesh.indexStart,
  33008. indexCount: subMesh.indexCount
  33009. });
  33010. }
  33011. }
  33012. // Material
  33013. if (this.material) {
  33014. serializationObject.materialId = this.material.id;
  33015. }
  33016. else {
  33017. this.material = null;
  33018. }
  33019. // Morph targets
  33020. if (this.morphTargetManager) {
  33021. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33022. }
  33023. // Skeleton
  33024. if (this.skeleton) {
  33025. serializationObject.skeletonId = this.skeleton.id;
  33026. }
  33027. // Physics
  33028. //TODO implement correct serialization for physics impostors.
  33029. var impostor = this.getPhysicsImpostor();
  33030. if (impostor) {
  33031. serializationObject.physicsMass = impostor.getParam("mass");
  33032. serializationObject.physicsFriction = impostor.getParam("friction");
  33033. serializationObject.physicsRestitution = impostor.getParam("mass");
  33034. serializationObject.physicsImpostor = impostor.type;
  33035. }
  33036. // Metadata
  33037. if (this.metadata) {
  33038. serializationObject.metadata = this.metadata;
  33039. }
  33040. // Instances
  33041. serializationObject.instances = [];
  33042. for (var index = 0; index < this.instances.length; index++) {
  33043. var instance = this.instances[index];
  33044. var serializationInstance = {
  33045. name: instance.name,
  33046. id: instance.id,
  33047. position: instance.position.asArray(),
  33048. scaling: instance.scaling.asArray()
  33049. };
  33050. if (instance.rotationQuaternion) {
  33051. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33052. }
  33053. else if (instance.rotation) {
  33054. serializationInstance.rotation = instance.rotation.asArray();
  33055. }
  33056. serializationObject.instances.push(serializationInstance);
  33057. // Animations
  33058. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33059. serializationInstance.ranges = instance.serializeAnimationRanges();
  33060. }
  33061. //
  33062. // Animations
  33063. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33064. serializationObject.ranges = this.serializeAnimationRanges();
  33065. // Layer mask
  33066. serializationObject.layerMask = this.layerMask;
  33067. // Alpha
  33068. serializationObject.alphaIndex = this.alphaIndex;
  33069. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33070. // Overlay
  33071. serializationObject.overlayAlpha = this.overlayAlpha;
  33072. serializationObject.overlayColor = this.overlayColor.asArray();
  33073. serializationObject.renderOverlay = this.renderOverlay;
  33074. // Fog
  33075. serializationObject.applyFog = this.applyFog;
  33076. // Action Manager
  33077. if (this.actionManager) {
  33078. serializationObject.actions = this.actionManager.serialize(this.name);
  33079. }
  33080. };
  33081. /** @hidden */
  33082. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33083. if (!this.geometry) {
  33084. return;
  33085. }
  33086. this._markSubMeshesAsAttributesDirty();
  33087. var morphTargetManager = this._morphTargetManager;
  33088. if (morphTargetManager && morphTargetManager.vertexCount) {
  33089. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33090. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33091. this.morphTargetManager = null;
  33092. return;
  33093. }
  33094. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33095. var morphTarget = morphTargetManager.getActiveTarget(index);
  33096. var positions = morphTarget.getPositions();
  33097. if (!positions) {
  33098. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33099. return;
  33100. }
  33101. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33102. var normals = morphTarget.getNormals();
  33103. if (normals) {
  33104. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33105. }
  33106. var tangents = morphTarget.getTangents();
  33107. if (tangents) {
  33108. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33109. }
  33110. }
  33111. }
  33112. else {
  33113. var index = 0;
  33114. // Positions
  33115. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33116. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33117. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33118. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33119. }
  33120. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33121. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33122. }
  33123. index++;
  33124. }
  33125. }
  33126. };
  33127. // Statics
  33128. /**
  33129. * Returns a new Mesh object parsed from the source provided.
  33130. * The parameter `parsedMesh` is the source.
  33131. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33132. */
  33133. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33134. var mesh;
  33135. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33136. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33137. }
  33138. else {
  33139. mesh = new Mesh(parsedMesh.name, scene);
  33140. }
  33141. mesh.id = parsedMesh.id;
  33142. if (BABYLON.Tags) {
  33143. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33144. }
  33145. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33146. if (parsedMesh.metadata !== undefined) {
  33147. mesh.metadata = parsedMesh.metadata;
  33148. }
  33149. if (parsedMesh.rotationQuaternion) {
  33150. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33151. }
  33152. else if (parsedMesh.rotation) {
  33153. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33154. }
  33155. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33156. if (parsedMesh.localMatrix) {
  33157. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33158. }
  33159. else if (parsedMesh.pivotMatrix) {
  33160. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33161. }
  33162. mesh.setEnabled(parsedMesh.isEnabled);
  33163. mesh.isVisible = parsedMesh.isVisible;
  33164. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33165. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33166. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33167. if (parsedMesh.applyFog !== undefined) {
  33168. mesh.applyFog = parsedMesh.applyFog;
  33169. }
  33170. if (parsedMesh.pickable !== undefined) {
  33171. mesh.isPickable = parsedMesh.pickable;
  33172. }
  33173. if (parsedMesh.alphaIndex !== undefined) {
  33174. mesh.alphaIndex = parsedMesh.alphaIndex;
  33175. }
  33176. mesh.receiveShadows = parsedMesh.receiveShadows;
  33177. mesh.billboardMode = parsedMesh.billboardMode;
  33178. if (parsedMesh.visibility !== undefined) {
  33179. mesh.visibility = parsedMesh.visibility;
  33180. }
  33181. mesh.checkCollisions = parsedMesh.checkCollisions;
  33182. if (parsedMesh.isBlocker !== undefined) {
  33183. mesh.isBlocker = parsedMesh.isBlocker;
  33184. }
  33185. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33186. // freezeWorldMatrix
  33187. if (parsedMesh.freezeWorldMatrix) {
  33188. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33189. }
  33190. // Parent
  33191. if (parsedMesh.parentId) {
  33192. mesh._waitingParentId = parsedMesh.parentId;
  33193. }
  33194. // Actions
  33195. if (parsedMesh.actions !== undefined) {
  33196. mesh._waitingActions = parsedMesh.actions;
  33197. }
  33198. // Overlay
  33199. if (parsedMesh.overlayAlpha !== undefined) {
  33200. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33201. }
  33202. if (parsedMesh.overlayColor !== undefined) {
  33203. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33204. }
  33205. if (parsedMesh.renderOverlay !== undefined) {
  33206. mesh.renderOverlay = parsedMesh.renderOverlay;
  33207. }
  33208. // Geometry
  33209. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33210. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33211. if (parsedMesh.delayLoadingFile) {
  33212. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33213. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33214. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33215. if (parsedMesh._binaryInfo) {
  33216. mesh._binaryInfo = parsedMesh._binaryInfo;
  33217. }
  33218. mesh._delayInfo = [];
  33219. if (parsedMesh.hasUVs) {
  33220. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33221. }
  33222. if (parsedMesh.hasUVs2) {
  33223. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33224. }
  33225. if (parsedMesh.hasUVs3) {
  33226. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33227. }
  33228. if (parsedMesh.hasUVs4) {
  33229. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33230. }
  33231. if (parsedMesh.hasUVs5) {
  33232. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33233. }
  33234. if (parsedMesh.hasUVs6) {
  33235. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33236. }
  33237. if (parsedMesh.hasColors) {
  33238. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33239. }
  33240. if (parsedMesh.hasMatricesIndices) {
  33241. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33242. }
  33243. if (parsedMesh.hasMatricesWeights) {
  33244. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33245. }
  33246. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33247. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33248. mesh._checkDelayState();
  33249. }
  33250. }
  33251. else {
  33252. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33253. }
  33254. // Material
  33255. if (parsedMesh.materialId) {
  33256. mesh.setMaterialByID(parsedMesh.materialId);
  33257. }
  33258. else {
  33259. mesh.material = null;
  33260. }
  33261. // Morph targets
  33262. if (parsedMesh.morphTargetManagerId > -1) {
  33263. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33264. }
  33265. // Skeleton
  33266. if (parsedMesh.skeletonId > -1) {
  33267. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33268. if (parsedMesh.numBoneInfluencers) {
  33269. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33270. }
  33271. }
  33272. // Animations
  33273. if (parsedMesh.animations) {
  33274. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33275. var parsedAnimation = parsedMesh.animations[animationIndex];
  33276. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33277. }
  33278. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33279. }
  33280. if (parsedMesh.autoAnimate) {
  33281. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33282. }
  33283. // Layer Mask
  33284. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33285. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33286. }
  33287. else {
  33288. mesh.layerMask = 0x0FFFFFFF;
  33289. }
  33290. // Physics
  33291. if (parsedMesh.physicsImpostor) {
  33292. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33293. mass: parsedMesh.physicsMass,
  33294. friction: parsedMesh.physicsFriction,
  33295. restitution: parsedMesh.physicsRestitution
  33296. }, scene);
  33297. }
  33298. // Instances
  33299. if (parsedMesh.instances) {
  33300. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33301. var parsedInstance = parsedMesh.instances[index];
  33302. var instance = mesh.createInstance(parsedInstance.name);
  33303. if (parsedInstance.id) {
  33304. instance.id = parsedInstance.id;
  33305. }
  33306. if (BABYLON.Tags) {
  33307. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33308. }
  33309. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33310. if (parsedInstance.parentId) {
  33311. instance._waitingParentId = parsedInstance.parentId;
  33312. }
  33313. if (parsedInstance.rotationQuaternion) {
  33314. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33315. }
  33316. else if (parsedInstance.rotation) {
  33317. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33318. }
  33319. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33320. instance.checkCollisions = mesh.checkCollisions;
  33321. if (parsedMesh.animations) {
  33322. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33323. parsedAnimation = parsedMesh.animations[animationIndex];
  33324. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33325. }
  33326. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33327. if (parsedMesh.autoAnimate) {
  33328. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33329. }
  33330. }
  33331. }
  33332. }
  33333. return mesh;
  33334. };
  33335. /**
  33336. * Creates a ribbon mesh.
  33337. * Please consider using the same method from the MeshBuilder class instead.
  33338. * 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.
  33339. *
  33340. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33341. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33342. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33343. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33344. * 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.
  33345. * 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.
  33346. * 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
  33347. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33348. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33349. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33350. */
  33351. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33352. if (closeArray === void 0) { closeArray = false; }
  33353. if (updatable === void 0) { updatable = false; }
  33354. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33355. pathArray: pathArray,
  33356. closeArray: closeArray,
  33357. closePath: closePath,
  33358. offset: offset,
  33359. updatable: updatable,
  33360. sideOrientation: sideOrientation,
  33361. instance: instance
  33362. }, scene);
  33363. };
  33364. /**
  33365. * Creates a plane polygonal mesh. By default, this is a disc.
  33366. * Please consider using the same method from the MeshBuilder class instead.
  33367. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33368. * 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.
  33369. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33370. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33371. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33372. */
  33373. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33374. if (scene === void 0) { scene = null; }
  33375. var options = {
  33376. radius: radius,
  33377. tessellation: tessellation,
  33378. sideOrientation: sideOrientation,
  33379. updatable: updatable
  33380. };
  33381. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33382. };
  33383. /**
  33384. * Creates a box mesh.
  33385. * Please consider using the same method from the MeshBuilder class instead.
  33386. * The parameter `size` sets the size (float) of each box side (default 1).
  33387. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33388. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33390. */
  33391. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33392. if (scene === void 0) { scene = null; }
  33393. var options = {
  33394. size: size,
  33395. sideOrientation: sideOrientation,
  33396. updatable: updatable
  33397. };
  33398. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33399. };
  33400. /**
  33401. * Creates a sphere mesh.
  33402. * Please consider using the same method from the MeshBuilder class instead.
  33403. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33404. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33405. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33406. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33407. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33408. */
  33409. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33410. var options = {
  33411. segments: segments,
  33412. diameterX: diameter,
  33413. diameterY: diameter,
  33414. diameterZ: diameter,
  33415. sideOrientation: sideOrientation,
  33416. updatable: updatable
  33417. };
  33418. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33419. };
  33420. /**
  33421. * Creates a cylinder or a cone mesh.
  33422. * Please consider using the same method from the MeshBuilder class instead.
  33423. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33424. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33425. * 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.
  33426. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33427. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33428. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33429. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33430. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33431. */
  33432. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33433. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33434. if (scene !== undefined) {
  33435. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33436. updatable = scene;
  33437. }
  33438. scene = subdivisions;
  33439. subdivisions = 1;
  33440. }
  33441. var options = {
  33442. height: height,
  33443. diameterTop: diameterTop,
  33444. diameterBottom: diameterBottom,
  33445. tessellation: tessellation,
  33446. subdivisions: subdivisions,
  33447. sideOrientation: sideOrientation,
  33448. updatable: updatable
  33449. };
  33450. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33451. };
  33452. // Torus (Code from SharpDX.org)
  33453. /**
  33454. * Creates a torus mesh.
  33455. * Please consider using the same method from the MeshBuilder class instead.
  33456. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33457. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33458. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33459. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33460. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33462. */
  33463. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33464. var options = {
  33465. diameter: diameter,
  33466. thickness: thickness,
  33467. tessellation: tessellation,
  33468. sideOrientation: sideOrientation,
  33469. updatable: updatable
  33470. };
  33471. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33472. };
  33473. /**
  33474. * Creates a torus knot mesh.
  33475. * Please consider using the same method from the MeshBuilder class instead.
  33476. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33477. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33478. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33479. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33480. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33481. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33482. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33483. */
  33484. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33485. var options = {
  33486. radius: radius,
  33487. tube: tube,
  33488. radialSegments: radialSegments,
  33489. tubularSegments: tubularSegments,
  33490. p: p,
  33491. q: q,
  33492. sideOrientation: sideOrientation,
  33493. updatable: updatable
  33494. };
  33495. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33496. };
  33497. /**
  33498. * Creates a line mesh.
  33499. * Please consider using the same method from the MeshBuilder class instead.
  33500. * 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.
  33501. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33502. * The parameter `points` is an array successive Vector3.
  33503. * 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
  33504. * When updating an instance, remember that only point positions can change, not the number of points.
  33505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33506. */
  33507. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33508. if (scene === void 0) { scene = null; }
  33509. if (updatable === void 0) { updatable = false; }
  33510. if (instance === void 0) { instance = null; }
  33511. var options = {
  33512. points: points,
  33513. updatable: updatable,
  33514. instance: instance
  33515. };
  33516. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33517. };
  33518. /**
  33519. * Creates a dashed line mesh.
  33520. * Please consider using the same method from the MeshBuilder class instead.
  33521. * 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.
  33522. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33523. * The parameter `points` is an array successive Vector3.
  33524. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33525. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33526. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33527. * 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
  33528. * When updating an instance, remember that only point positions can change, not the number of points.
  33529. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33530. */
  33531. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33532. if (scene === void 0) { scene = null; }
  33533. var options = {
  33534. points: points,
  33535. dashSize: dashSize,
  33536. gapSize: gapSize,
  33537. dashNb: dashNb,
  33538. updatable: updatable,
  33539. instance: instance
  33540. };
  33541. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33542. };
  33543. /**
  33544. * Creates a polygon mesh.
  33545. * Please consider using the same method from the MeshBuilder class instead.
  33546. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33547. * 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.
  33548. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33549. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33550. * Remember you can only change the shape positions, not their number when updating a polygon.
  33551. */
  33552. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33553. var options = {
  33554. shape: shape,
  33555. holes: holes,
  33556. updatable: updatable,
  33557. sideOrientation: sideOrientation
  33558. };
  33559. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33560. };
  33561. /**
  33562. * Creates an extruded polygon mesh, with depth in the Y direction.
  33563. * Please consider using the same method from the MeshBuilder class instead.
  33564. */
  33565. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33566. var options = {
  33567. shape: shape,
  33568. holes: holes,
  33569. depth: depth,
  33570. updatable: updatable,
  33571. sideOrientation: sideOrientation
  33572. };
  33573. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33574. };
  33575. /**
  33576. * Creates an extruded shape mesh.
  33577. * 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.
  33578. * Please consider using the same method from the MeshBuilder class instead.
  33579. *
  33580. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33581. * 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
  33582. * extruded along the Z axis.
  33583. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33584. * 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.
  33585. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33586. * 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
  33587. * 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
  33588. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33589. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33590. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33591. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33592. */
  33593. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33594. if (scene === void 0) { scene = null; }
  33595. var options = {
  33596. shape: shape,
  33597. path: path,
  33598. scale: scale,
  33599. rotation: rotation,
  33600. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33601. sideOrientation: sideOrientation,
  33602. instance: instance,
  33603. updatable: updatable
  33604. };
  33605. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33606. };
  33607. /**
  33608. * Creates an custom extruded shape mesh.
  33609. * 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.
  33610. * Please consider using the same method from the MeshBuilder class instead.
  33611. *
  33612. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33613. * 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
  33614. * extruded along the Z axis.
  33615. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33616. * 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
  33617. * and the distance of this point from the begining of the path :
  33618. * ```javascript
  33619. * var rotationFunction = function(i, distance) {
  33620. * // do things
  33621. * return rotationValue; }
  33622. * ```
  33623. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33624. * 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
  33625. * and the distance of this point from the begining of the path :
  33626. * ```javascript
  33627. * var scaleFunction = function(i, distance) {
  33628. * // do things
  33629. * return scaleValue;}
  33630. * ```
  33631. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33632. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33633. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33634. * 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
  33635. * 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
  33636. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33637. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33638. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33640. */
  33641. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33642. var options = {
  33643. shape: shape,
  33644. path: path,
  33645. scaleFunction: scaleFunction,
  33646. rotationFunction: rotationFunction,
  33647. ribbonCloseArray: ribbonCloseArray,
  33648. ribbonClosePath: ribbonClosePath,
  33649. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33650. sideOrientation: sideOrientation,
  33651. instance: instance,
  33652. updatable: updatable
  33653. };
  33654. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33655. };
  33656. /**
  33657. * Creates lathe mesh.
  33658. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33659. * Please consider using the same method from the MeshBuilder class instead.
  33660. * 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
  33661. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33662. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33663. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33664. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33665. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33667. */
  33668. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33669. var options = {
  33670. shape: shape,
  33671. radius: radius,
  33672. tessellation: tessellation,
  33673. sideOrientation: sideOrientation,
  33674. updatable: updatable
  33675. };
  33676. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33677. };
  33678. /**
  33679. * Creates a plane mesh.
  33680. * Please consider using the same method from the MeshBuilder class instead.
  33681. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33682. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33683. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33684. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33685. */
  33686. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33687. var options = {
  33688. size: size,
  33689. width: size,
  33690. height: size,
  33691. sideOrientation: sideOrientation,
  33692. updatable: updatable
  33693. };
  33694. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33695. };
  33696. /**
  33697. * Creates a ground mesh.
  33698. * Please consider using the same method from the MeshBuilder class instead.
  33699. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33700. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33701. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33702. */
  33703. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33704. var options = {
  33705. width: width,
  33706. height: height,
  33707. subdivisions: subdivisions,
  33708. updatable: updatable
  33709. };
  33710. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33711. };
  33712. /**
  33713. * Creates a tiled ground mesh.
  33714. * Please consider using the same method from the MeshBuilder class instead.
  33715. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33716. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33717. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33718. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33719. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33720. * numbers of subdivisions on the ground width and height of each tile.
  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.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33724. var options = {
  33725. xmin: xmin,
  33726. zmin: zmin,
  33727. xmax: xmax,
  33728. zmax: zmax,
  33729. subdivisions: subdivisions,
  33730. precision: precision,
  33731. updatable: updatable
  33732. };
  33733. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33734. };
  33735. /**
  33736. * Creates a ground mesh from a height map.
  33737. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33738. * Please consider using the same method from the MeshBuilder class instead.
  33739. * The parameter `url` sets the URL of the height map image resource.
  33740. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33741. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33742. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33743. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33744. * 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).
  33745. * This function is passed the newly built mesh :
  33746. * ```javascript
  33747. * function(mesh) { // do things
  33748. * return; }
  33749. * ```
  33750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33751. */
  33752. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33753. var options = {
  33754. width: width,
  33755. height: height,
  33756. subdivisions: subdivisions,
  33757. minHeight: minHeight,
  33758. maxHeight: maxHeight,
  33759. updatable: updatable,
  33760. onReady: onReady
  33761. };
  33762. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33763. };
  33764. /**
  33765. * Creates a tube mesh.
  33766. * 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.
  33767. * Please consider using the same method from the MeshBuilder class instead.
  33768. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33769. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33770. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33771. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33772. * 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.
  33773. * It must return a radius value (positive float) :
  33774. * ```javascript
  33775. * var radiusFunction = function(i, distance) {
  33776. * // do things
  33777. * return radius; }
  33778. * ```
  33779. * 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
  33780. * 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
  33781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33782. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33784. */
  33785. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33786. var options = {
  33787. path: path,
  33788. radius: radius,
  33789. tessellation: tessellation,
  33790. radiusFunction: radiusFunction,
  33791. arc: 1,
  33792. cap: cap,
  33793. updatable: updatable,
  33794. sideOrientation: sideOrientation,
  33795. instance: instance
  33796. };
  33797. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33798. };
  33799. /**
  33800. * Creates a polyhedron mesh.
  33801. * Please consider using the same method from the MeshBuilder class instead.
  33802. * 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
  33803. * to choose the wanted type.
  33804. * The parameter `size` (positive float, default 1) sets the polygon size.
  33805. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33806. * 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`.
  33807. * 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
  33808. * 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)`).
  33809. * 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
  33810. * 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.
  33811. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33812. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33814. */
  33815. Mesh.CreatePolyhedron = function (name, options, scene) {
  33816. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33817. };
  33818. /**
  33819. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33820. * Please consider using the same method from the MeshBuilder class instead.
  33821. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33822. * 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`).
  33823. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33824. * 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.
  33825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33826. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33828. */
  33829. Mesh.CreateIcoSphere = function (name, options, scene) {
  33830. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33831. };
  33832. /**
  33833. * Creates a decal mesh.
  33834. * Please consider using the same method from the MeshBuilder class instead.
  33835. * 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.
  33836. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33837. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33838. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33839. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33840. */
  33841. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33842. var options = {
  33843. position: position,
  33844. normal: normal,
  33845. size: size,
  33846. angle: angle
  33847. };
  33848. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33849. };
  33850. // Skeletons
  33851. /**
  33852. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33853. */
  33854. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33855. if (!this._sourcePositions) {
  33856. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33857. if (!source) {
  33858. return this._sourcePositions;
  33859. }
  33860. this._sourcePositions = new Float32Array(source);
  33861. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33862. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33863. }
  33864. }
  33865. return this._sourcePositions;
  33866. };
  33867. /**
  33868. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33869. */
  33870. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33871. if (!this._sourceNormals) {
  33872. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33873. if (!source) {
  33874. return this._sourceNormals;
  33875. }
  33876. this._sourceNormals = new Float32Array(source);
  33877. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33878. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33879. }
  33880. }
  33881. return this._sourceNormals;
  33882. };
  33883. /**
  33884. * Updates the vertex buffer by applying transformation from the bones.
  33885. * Returns the Mesh.
  33886. *
  33887. * @param {skeleton} skeleton to apply
  33888. */
  33889. Mesh.prototype.applySkeleton = function (skeleton) {
  33890. if (!this.geometry) {
  33891. return this;
  33892. }
  33893. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33894. return this;
  33895. }
  33896. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33897. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33898. return this;
  33899. }
  33900. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33901. return this;
  33902. }
  33903. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33904. return this;
  33905. }
  33906. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33907. return this;
  33908. }
  33909. if (!this._sourcePositions) {
  33910. var submeshes = this.subMeshes.slice();
  33911. this.setPositionsForCPUSkinning();
  33912. this.subMeshes = submeshes;
  33913. }
  33914. if (!this._sourceNormals) {
  33915. this.setNormalsForCPUSkinning();
  33916. }
  33917. // positionsData checks for not being Float32Array will only pass at most once
  33918. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33919. if (!positionsData) {
  33920. return this;
  33921. }
  33922. if (!(positionsData instanceof Float32Array)) {
  33923. positionsData = new Float32Array(positionsData);
  33924. }
  33925. // normalsData checks for not being Float32Array will only pass at most once
  33926. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33927. if (!normalsData) {
  33928. return this;
  33929. }
  33930. if (!(normalsData instanceof Float32Array)) {
  33931. normalsData = new Float32Array(normalsData);
  33932. }
  33933. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33934. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33935. if (!matricesWeightsData || !matricesIndicesData) {
  33936. return this;
  33937. }
  33938. var needExtras = this.numBoneInfluencers > 4;
  33939. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33940. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33941. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33942. var tempVector3 = BABYLON.Vector3.Zero();
  33943. var finalMatrix = new BABYLON.Matrix();
  33944. var tempMatrix = new BABYLON.Matrix();
  33945. var matWeightIdx = 0;
  33946. var inf;
  33947. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33948. var weight;
  33949. for (inf = 0; inf < 4; inf++) {
  33950. weight = matricesWeightsData[matWeightIdx + inf];
  33951. if (weight > 0) {
  33952. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33953. finalMatrix.addToSelf(tempMatrix);
  33954. }
  33955. }
  33956. if (needExtras) {
  33957. for (inf = 0; inf < 4; inf++) {
  33958. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33959. if (weight > 0) {
  33960. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33961. finalMatrix.addToSelf(tempMatrix);
  33962. }
  33963. }
  33964. }
  33965. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33966. tempVector3.toArray(positionsData, index);
  33967. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33968. tempVector3.toArray(normalsData, index);
  33969. finalMatrix.reset();
  33970. }
  33971. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33972. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33973. return this;
  33974. };
  33975. // Tools
  33976. /**
  33977. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33978. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33979. */
  33980. Mesh.MinMax = function (meshes) {
  33981. var minVector = null;
  33982. var maxVector = null;
  33983. meshes.forEach(function (mesh, index, array) {
  33984. var boundingInfo = mesh.getBoundingInfo();
  33985. var boundingBox = boundingInfo.boundingBox;
  33986. if (!minVector || !maxVector) {
  33987. minVector = boundingBox.minimumWorld;
  33988. maxVector = boundingBox.maximumWorld;
  33989. }
  33990. else {
  33991. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33992. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33993. }
  33994. });
  33995. if (!minVector || !maxVector) {
  33996. return {
  33997. min: BABYLON.Vector3.Zero(),
  33998. max: BABYLON.Vector3.Zero()
  33999. };
  34000. }
  34001. return {
  34002. min: minVector,
  34003. max: maxVector
  34004. };
  34005. };
  34006. /**
  34007. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34008. */
  34009. Mesh.Center = function (meshesOrMinMaxVector) {
  34010. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34011. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34012. };
  34013. /**
  34014. * Merge the array of meshes into a single mesh for performance reasons.
  34015. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34016. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34017. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34018. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34019. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34020. */
  34021. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34022. if (disposeSource === void 0) { disposeSource = true; }
  34023. var index;
  34024. if (!allow32BitsIndices) {
  34025. var totalVertices = 0;
  34026. // Counting vertices
  34027. for (index = 0; index < meshes.length; index++) {
  34028. if (meshes[index]) {
  34029. totalVertices += meshes[index].getTotalVertices();
  34030. if (totalVertices > 65536) {
  34031. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34032. return null;
  34033. }
  34034. }
  34035. }
  34036. }
  34037. // Merge
  34038. var vertexData = null;
  34039. var otherVertexData;
  34040. var indiceArray = new Array();
  34041. var source = null;
  34042. for (index = 0; index < meshes.length; index++) {
  34043. if (meshes[index]) {
  34044. meshes[index].computeWorldMatrix(true);
  34045. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34046. otherVertexData.transform(meshes[index].getWorldMatrix());
  34047. if (vertexData) {
  34048. vertexData.merge(otherVertexData);
  34049. }
  34050. else {
  34051. vertexData = otherVertexData;
  34052. source = meshes[index];
  34053. }
  34054. if (subdivideWithSubMeshes) {
  34055. indiceArray.push(meshes[index].getTotalIndices());
  34056. }
  34057. }
  34058. }
  34059. source = source;
  34060. if (!meshSubclass) {
  34061. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34062. }
  34063. vertexData.applyToMesh(meshSubclass);
  34064. // Setting properties
  34065. meshSubclass.material = source.material;
  34066. meshSubclass.checkCollisions = source.checkCollisions;
  34067. // Cleaning
  34068. if (disposeSource) {
  34069. for (index = 0; index < meshes.length; index++) {
  34070. if (meshes[index]) {
  34071. meshes[index].dispose();
  34072. }
  34073. }
  34074. }
  34075. // Subdivide
  34076. if (subdivideWithSubMeshes) {
  34077. //-- removal of global submesh
  34078. meshSubclass.releaseSubMeshes();
  34079. index = 0;
  34080. var offset = 0;
  34081. //-- apply subdivision according to index table
  34082. while (index < indiceArray.length) {
  34083. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34084. offset += indiceArray[index];
  34085. index++;
  34086. }
  34087. }
  34088. return meshSubclass;
  34089. };
  34090. // Consts
  34091. Mesh._FRONTSIDE = 0;
  34092. Mesh._BACKSIDE = 1;
  34093. Mesh._DOUBLESIDE = 2;
  34094. Mesh._DEFAULTSIDE = 0;
  34095. Mesh._NO_CAP = 0;
  34096. Mesh._CAP_START = 1;
  34097. Mesh._CAP_END = 2;
  34098. Mesh._CAP_ALL = 3;
  34099. return Mesh;
  34100. }(BABYLON.AbstractMesh));
  34101. BABYLON.Mesh = Mesh;
  34102. })(BABYLON || (BABYLON = {}));
  34103. //# sourceMappingURL=babylon.mesh.js.map
  34104. var BABYLON;
  34105. (function (BABYLON) {
  34106. var BaseSubMesh = /** @class */ (function () {
  34107. function BaseSubMesh() {
  34108. }
  34109. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34110. get: function () {
  34111. return this._materialEffect;
  34112. },
  34113. enumerable: true,
  34114. configurable: true
  34115. });
  34116. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34117. if (defines === void 0) { defines = null; }
  34118. if (this._materialEffect === effect) {
  34119. if (!effect) {
  34120. this._materialDefines = null;
  34121. }
  34122. return;
  34123. }
  34124. this._materialDefines = defines;
  34125. this._materialEffect = effect;
  34126. };
  34127. return BaseSubMesh;
  34128. }());
  34129. BABYLON.BaseSubMesh = BaseSubMesh;
  34130. var SubMesh = /** @class */ (function (_super) {
  34131. __extends(SubMesh, _super);
  34132. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34133. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34134. var _this = _super.call(this) || this;
  34135. _this.materialIndex = materialIndex;
  34136. _this.verticesStart = verticesStart;
  34137. _this.verticesCount = verticesCount;
  34138. _this.indexStart = indexStart;
  34139. _this.indexCount = indexCount;
  34140. /** @hidden */
  34141. _this._renderId = 0;
  34142. _this._mesh = mesh;
  34143. _this._renderingMesh = renderingMesh || mesh;
  34144. mesh.subMeshes.push(_this);
  34145. _this._trianglePlanes = [];
  34146. _this._id = mesh.subMeshes.length - 1;
  34147. if (createBoundingBox) {
  34148. _this.refreshBoundingInfo();
  34149. mesh.computeWorldMatrix(true);
  34150. }
  34151. return _this;
  34152. }
  34153. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34154. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34155. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34156. };
  34157. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34158. get: function () {
  34159. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34160. },
  34161. enumerable: true,
  34162. configurable: true
  34163. });
  34164. /**
  34165. * Returns the submesh BoudingInfo object.
  34166. */
  34167. SubMesh.prototype.getBoundingInfo = function () {
  34168. if (this.IsGlobal) {
  34169. return this._mesh.getBoundingInfo();
  34170. }
  34171. return this._boundingInfo;
  34172. };
  34173. /**
  34174. * Sets the submesh BoundingInfo.
  34175. * Return the SubMesh.
  34176. */
  34177. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34178. this._boundingInfo = boundingInfo;
  34179. return this;
  34180. };
  34181. /**
  34182. * Returns the mesh of the current submesh.
  34183. */
  34184. SubMesh.prototype.getMesh = function () {
  34185. return this._mesh;
  34186. };
  34187. /**
  34188. * Returns the rendering mesh of the submesh.
  34189. */
  34190. SubMesh.prototype.getRenderingMesh = function () {
  34191. return this._renderingMesh;
  34192. };
  34193. /**
  34194. * Returns the submesh material.
  34195. */
  34196. SubMesh.prototype.getMaterial = function () {
  34197. var rootMaterial = this._renderingMesh.material;
  34198. if (rootMaterial === null || rootMaterial === undefined) {
  34199. return this._mesh.getScene().defaultMaterial;
  34200. }
  34201. else if (rootMaterial.getSubMaterial) {
  34202. var multiMaterial = rootMaterial;
  34203. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34204. if (this._currentMaterial !== effectiveMaterial) {
  34205. this._currentMaterial = effectiveMaterial;
  34206. this._materialDefines = null;
  34207. }
  34208. return effectiveMaterial;
  34209. }
  34210. return rootMaterial;
  34211. };
  34212. // Methods
  34213. /**
  34214. * Sets a new updated BoundingInfo object to the submesh.
  34215. * Returns the SubMesh.
  34216. */
  34217. SubMesh.prototype.refreshBoundingInfo = function () {
  34218. this._lastColliderWorldVertices = null;
  34219. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34220. return this;
  34221. }
  34222. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34223. if (!data) {
  34224. this._boundingInfo = this._mesh.getBoundingInfo();
  34225. return this;
  34226. }
  34227. var indices = this._renderingMesh.getIndices();
  34228. var extend;
  34229. //is this the only submesh?
  34230. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34231. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34232. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34233. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34234. }
  34235. else {
  34236. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34237. }
  34238. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34239. return this;
  34240. };
  34241. /** @hidden */
  34242. SubMesh.prototype._checkCollision = function (collider) {
  34243. var boundingInfo = this.getBoundingInfo();
  34244. return boundingInfo._checkCollision(collider);
  34245. };
  34246. /**
  34247. * Updates the submesh BoundingInfo.
  34248. * Returns the Submesh.
  34249. */
  34250. SubMesh.prototype.updateBoundingInfo = function (world) {
  34251. var boundingInfo = this.getBoundingInfo();
  34252. if (!boundingInfo) {
  34253. this.refreshBoundingInfo();
  34254. boundingInfo = this.getBoundingInfo();
  34255. }
  34256. boundingInfo.update(world);
  34257. return this;
  34258. };
  34259. /**
  34260. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34261. * Boolean returned.
  34262. */
  34263. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34264. var boundingInfo = this.getBoundingInfo();
  34265. if (!boundingInfo) {
  34266. return false;
  34267. }
  34268. return boundingInfo.isInFrustum(frustumPlanes);
  34269. };
  34270. /**
  34271. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34272. * Boolean returned.
  34273. */
  34274. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34275. var boundingInfo = this.getBoundingInfo();
  34276. if (!boundingInfo) {
  34277. return false;
  34278. }
  34279. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34280. };
  34281. /**
  34282. * Renders the submesh.
  34283. * Returns it.
  34284. */
  34285. SubMesh.prototype.render = function (enableAlphaMode) {
  34286. this._renderingMesh.render(this, enableAlphaMode);
  34287. return this;
  34288. };
  34289. /**
  34290. * Returns a new Index Buffer.
  34291. * Type returned : WebGLBuffer.
  34292. */
  34293. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34294. if (!this._linesIndexBuffer) {
  34295. var linesIndices = [];
  34296. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34297. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34298. }
  34299. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34300. this.linesIndexCount = linesIndices.length;
  34301. }
  34302. return this._linesIndexBuffer;
  34303. };
  34304. /**
  34305. * True is the passed Ray intersects the submesh bounding box.
  34306. * Boolean returned.
  34307. */
  34308. SubMesh.prototype.canIntersects = function (ray) {
  34309. var boundingInfo = this.getBoundingInfo();
  34310. if (!boundingInfo) {
  34311. return false;
  34312. }
  34313. return ray.intersectsBox(boundingInfo.boundingBox);
  34314. };
  34315. /**
  34316. * Returns an object IntersectionInfo.
  34317. */
  34318. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34319. var intersectInfo = null;
  34320. var material = this.getMaterial();
  34321. if (!material) {
  34322. return null;
  34323. }
  34324. switch (material.fillMode) {
  34325. case BABYLON.Material.PointListDrawMode:
  34326. case BABYLON.Material.LineListDrawMode:
  34327. case BABYLON.Material.LineLoopDrawMode:
  34328. case BABYLON.Material.LineStripDrawMode:
  34329. case BABYLON.Material.TriangleFanDrawMode:
  34330. case BABYLON.Material.TriangleStripDrawMode:
  34331. return null;
  34332. }
  34333. // LineMesh first as it's also a Mesh...
  34334. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34335. var lineMesh = this._mesh;
  34336. // Line test
  34337. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34338. var p0 = positions[indices[index]];
  34339. var p1 = positions[indices[index + 1]];
  34340. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34341. if (length < 0) {
  34342. continue;
  34343. }
  34344. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34345. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34346. if (fastCheck) {
  34347. break;
  34348. }
  34349. }
  34350. }
  34351. }
  34352. else {
  34353. // Triangles test
  34354. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34355. var p0 = positions[indices[index]];
  34356. var p1 = positions[indices[index + 1]];
  34357. var p2 = positions[indices[index + 2]];
  34358. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34359. if (currentIntersectInfo) {
  34360. if (currentIntersectInfo.distance < 0) {
  34361. continue;
  34362. }
  34363. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34364. intersectInfo = currentIntersectInfo;
  34365. intersectInfo.faceId = index / 3;
  34366. if (fastCheck) {
  34367. break;
  34368. }
  34369. }
  34370. }
  34371. }
  34372. }
  34373. return intersectInfo;
  34374. };
  34375. /** @hidden */
  34376. SubMesh.prototype._rebuild = function () {
  34377. if (this._linesIndexBuffer) {
  34378. this._linesIndexBuffer = null;
  34379. }
  34380. };
  34381. // Clone
  34382. /**
  34383. * Creates a new Submesh from the passed Mesh.
  34384. */
  34385. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34386. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34387. if (!this.IsGlobal) {
  34388. var boundingInfo = this.getBoundingInfo();
  34389. if (!boundingInfo) {
  34390. return result;
  34391. }
  34392. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34393. }
  34394. return result;
  34395. };
  34396. // Dispose
  34397. /**
  34398. * Disposes the Submesh.
  34399. * Returns nothing.
  34400. */
  34401. SubMesh.prototype.dispose = function () {
  34402. if (this._linesIndexBuffer) {
  34403. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34404. this._linesIndexBuffer = null;
  34405. }
  34406. // Remove from mesh
  34407. var index = this._mesh.subMeshes.indexOf(this);
  34408. this._mesh.subMeshes.splice(index, 1);
  34409. };
  34410. // Statics
  34411. /**
  34412. * Creates a new Submesh from the passed parameters :
  34413. * - materialIndex (integer) : the index of the main mesh material.
  34414. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34415. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34416. * - mesh (Mesh) : the main mesh to create the submesh from.
  34417. * - renderingMesh (optional Mesh) : rendering mesh.
  34418. */
  34419. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34420. var minVertexIndex = Number.MAX_VALUE;
  34421. var maxVertexIndex = -Number.MAX_VALUE;
  34422. renderingMesh = (renderingMesh || mesh);
  34423. var indices = renderingMesh.getIndices();
  34424. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34425. var vertexIndex = indices[index];
  34426. if (vertexIndex < minVertexIndex)
  34427. minVertexIndex = vertexIndex;
  34428. if (vertexIndex > maxVertexIndex)
  34429. maxVertexIndex = vertexIndex;
  34430. }
  34431. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34432. };
  34433. return SubMesh;
  34434. }(BaseSubMesh));
  34435. BABYLON.SubMesh = SubMesh;
  34436. })(BABYLON || (BABYLON = {}));
  34437. //# sourceMappingURL=babylon.subMesh.js.map
  34438. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34439. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34440. s = arguments[i];
  34441. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34442. t[p] = s[p];
  34443. }
  34444. return t;
  34445. };
  34446. var BABYLON;
  34447. (function (BABYLON) {
  34448. /**
  34449. * Manages the defines for the Material
  34450. */
  34451. var MaterialDefines = /** @class */ (function () {
  34452. function MaterialDefines() {
  34453. this._isDirty = true;
  34454. /** @hidden */
  34455. this._areLightsDirty = true;
  34456. /** @hidden */
  34457. this._areAttributesDirty = true;
  34458. /** @hidden */
  34459. this._areTexturesDirty = true;
  34460. /** @hidden */
  34461. this._areFresnelDirty = true;
  34462. /** @hidden */
  34463. this._areMiscDirty = true;
  34464. /** @hidden */
  34465. this._areImageProcessingDirty = true;
  34466. /** @hidden */
  34467. this._normals = false;
  34468. /** @hidden */
  34469. this._uvs = false;
  34470. /** @hidden */
  34471. this._needNormals = false;
  34472. /** @hidden */
  34473. this._needUVs = false;
  34474. }
  34475. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34476. /**
  34477. * Specifies if the material needs to be re-calculated
  34478. */
  34479. get: function () {
  34480. return this._isDirty;
  34481. },
  34482. enumerable: true,
  34483. configurable: true
  34484. });
  34485. /**
  34486. * Marks the material to indicate that it has been re-calculated
  34487. */
  34488. MaterialDefines.prototype.markAsProcessed = function () {
  34489. this._isDirty = false;
  34490. this._areAttributesDirty = false;
  34491. this._areTexturesDirty = false;
  34492. this._areFresnelDirty = false;
  34493. this._areLightsDirty = false;
  34494. this._areMiscDirty = false;
  34495. this._areImageProcessingDirty = false;
  34496. };
  34497. /**
  34498. * Marks the material to indicate that it needs to be re-calculated
  34499. */
  34500. MaterialDefines.prototype.markAsUnprocessed = function () {
  34501. this._isDirty = true;
  34502. };
  34503. /**
  34504. * Marks the material to indicate all of its defines need to be re-calculated
  34505. */
  34506. MaterialDefines.prototype.markAllAsDirty = function () {
  34507. this._areTexturesDirty = true;
  34508. this._areAttributesDirty = true;
  34509. this._areLightsDirty = true;
  34510. this._areFresnelDirty = true;
  34511. this._areMiscDirty = true;
  34512. this._areImageProcessingDirty = true;
  34513. this._isDirty = true;
  34514. };
  34515. /**
  34516. * Marks the material to indicate that image processing needs to be re-calculated
  34517. */
  34518. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34519. this._areImageProcessingDirty = true;
  34520. this._isDirty = true;
  34521. };
  34522. /**
  34523. * Marks the material to indicate the lights need to be re-calculated
  34524. */
  34525. MaterialDefines.prototype.markAsLightDirty = function () {
  34526. this._areLightsDirty = true;
  34527. this._isDirty = true;
  34528. };
  34529. /**
  34530. * Marks the attribute state as changed
  34531. */
  34532. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34533. this._areAttributesDirty = true;
  34534. this._isDirty = true;
  34535. };
  34536. /**
  34537. * Marks the texture state as changed
  34538. */
  34539. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34540. this._areTexturesDirty = true;
  34541. this._isDirty = true;
  34542. };
  34543. /**
  34544. * Marks the fresnel state as changed
  34545. */
  34546. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34547. this._areFresnelDirty = true;
  34548. this._isDirty = true;
  34549. };
  34550. /**
  34551. * Marks the misc state as changed
  34552. */
  34553. MaterialDefines.prototype.markAsMiscDirty = function () {
  34554. this._areMiscDirty = true;
  34555. this._isDirty = true;
  34556. };
  34557. /**
  34558. * Rebuilds the material defines
  34559. */
  34560. MaterialDefines.prototype.rebuild = function () {
  34561. if (this._keys) {
  34562. delete this._keys;
  34563. }
  34564. this._keys = [];
  34565. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34566. var key = _a[_i];
  34567. if (key[0] === "_") {
  34568. continue;
  34569. }
  34570. this._keys.push(key);
  34571. }
  34572. };
  34573. /**
  34574. * Specifies if two material defines are equal
  34575. * @param other - A material define instance to compare to
  34576. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34577. */
  34578. MaterialDefines.prototype.isEqual = function (other) {
  34579. if (this._keys.length !== other._keys.length) {
  34580. return false;
  34581. }
  34582. for (var index = 0; index < this._keys.length; index++) {
  34583. var prop = this._keys[index];
  34584. if (this[prop] !== other[prop]) {
  34585. return false;
  34586. }
  34587. }
  34588. return true;
  34589. };
  34590. /**
  34591. * Clones this instance's defines to another instance
  34592. * @param other - material defines to clone values to
  34593. */
  34594. MaterialDefines.prototype.cloneTo = function (other) {
  34595. if (this._keys.length !== other._keys.length) {
  34596. other._keys = this._keys.slice(0);
  34597. }
  34598. for (var index = 0; index < this._keys.length; index++) {
  34599. var prop = this._keys[index];
  34600. other[prop] = this[prop];
  34601. }
  34602. };
  34603. /**
  34604. * Resets the material define values
  34605. */
  34606. MaterialDefines.prototype.reset = function () {
  34607. for (var index = 0; index < this._keys.length; index++) {
  34608. var prop = this._keys[index];
  34609. var type = typeof this[prop];
  34610. switch (type) {
  34611. case "number":
  34612. this[prop] = 0;
  34613. break;
  34614. case "string":
  34615. this[prop] = "";
  34616. break;
  34617. default:
  34618. this[prop] = false;
  34619. break;
  34620. }
  34621. }
  34622. };
  34623. /**
  34624. * Converts the material define values to a string
  34625. * @returns - String of material define information
  34626. */
  34627. MaterialDefines.prototype.toString = function () {
  34628. var result = "";
  34629. for (var index = 0; index < this._keys.length; index++) {
  34630. var prop = this._keys[index];
  34631. var value = this[prop];
  34632. var type = typeof value;
  34633. switch (type) {
  34634. case "number":
  34635. case "string":
  34636. result += "#define " + prop + " " + value + "\n";
  34637. break;
  34638. default:
  34639. if (value) {
  34640. result += "#define " + prop + "\n";
  34641. }
  34642. break;
  34643. }
  34644. }
  34645. return result;
  34646. };
  34647. return MaterialDefines;
  34648. }());
  34649. BABYLON.MaterialDefines = MaterialDefines;
  34650. /**
  34651. * Base class for the main features of a material in Babylon.js
  34652. */
  34653. var Material = /** @class */ (function () {
  34654. /**
  34655. * Creates a material instance
  34656. * @param name defines the name of the material
  34657. * @param scene defines the scene to reference
  34658. * @param doNotAdd specifies if the material should be added to the scene
  34659. */
  34660. function Material(name, scene, doNotAdd) {
  34661. /**
  34662. * Specifies if the ready state should be checked on each call
  34663. */
  34664. this.checkReadyOnEveryCall = false;
  34665. /**
  34666. * Specifies if the ready state should be checked once
  34667. */
  34668. this.checkReadyOnlyOnce = false;
  34669. /**
  34670. * The state of the material
  34671. */
  34672. this.state = "";
  34673. /**
  34674. * The alpha value of the material
  34675. */
  34676. this._alpha = 1.0;
  34677. /**
  34678. * Specifies if back face culling is enabled
  34679. */
  34680. this._backFaceCulling = true;
  34681. /**
  34682. * Specifies if the material should be serialized
  34683. */
  34684. this.doNotSerialize = false;
  34685. /**
  34686. * Specifies if the effect should be stored on sub meshes
  34687. */
  34688. this.storeEffectOnSubMeshes = false;
  34689. /**
  34690. * An event triggered when the material is disposed
  34691. */
  34692. this.onDisposeObservable = new BABYLON.Observable();
  34693. /**
  34694. * Stores the value of the alpha mode
  34695. */
  34696. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34697. /**
  34698. * Stores the state of the need depth pre-pass value
  34699. */
  34700. this._needDepthPrePass = false;
  34701. /**
  34702. * Specifies if depth writing should be disabled
  34703. */
  34704. this.disableDepthWrite = false;
  34705. /**
  34706. * Specifies if depth writing should be forced
  34707. */
  34708. this.forceDepthWrite = false;
  34709. /**
  34710. * Specifies if there should be a separate pass for culling
  34711. */
  34712. this.separateCullingPass = false;
  34713. /**
  34714. * Stores the state specifing if fog should be enabled
  34715. */
  34716. this._fogEnabled = true;
  34717. /**
  34718. * Stores the size of points
  34719. */
  34720. this.pointSize = 1.0;
  34721. /**
  34722. * Stores the z offset value
  34723. */
  34724. this.zOffset = 0;
  34725. /**
  34726. * @hidden
  34727. * Specifies if the material was previously ready
  34728. */
  34729. this._wasPreviouslyReady = false;
  34730. /**
  34731. * Stores the fill mode state
  34732. */
  34733. this._fillMode = Material.TriangleFillMode;
  34734. this.name = name;
  34735. this.id = name || BABYLON.Tools.RandomId();
  34736. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34737. this.uniqueId = this._scene.getUniqueId();
  34738. if (this._scene.useRightHandedSystem) {
  34739. this.sideOrientation = Material.ClockWiseSideOrientation;
  34740. }
  34741. else {
  34742. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34743. }
  34744. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34745. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34746. if (!doNotAdd) {
  34747. this._scene.materials.push(this);
  34748. }
  34749. }
  34750. Object.defineProperty(Material, "TriangleFillMode", {
  34751. /**
  34752. * Returns the triangle fill mode
  34753. */
  34754. get: function () {
  34755. return Material._TriangleFillMode;
  34756. },
  34757. enumerable: true,
  34758. configurable: true
  34759. });
  34760. Object.defineProperty(Material, "WireFrameFillMode", {
  34761. /**
  34762. * Returns the wireframe mode
  34763. */
  34764. get: function () {
  34765. return Material._WireFrameFillMode;
  34766. },
  34767. enumerable: true,
  34768. configurable: true
  34769. });
  34770. Object.defineProperty(Material, "PointFillMode", {
  34771. /**
  34772. * Returns the point fill mode
  34773. */
  34774. get: function () {
  34775. return Material._PointFillMode;
  34776. },
  34777. enumerable: true,
  34778. configurable: true
  34779. });
  34780. Object.defineProperty(Material, "PointListDrawMode", {
  34781. /**
  34782. * Returns the point list draw mode
  34783. */
  34784. get: function () {
  34785. return Material._PointListDrawMode;
  34786. },
  34787. enumerable: true,
  34788. configurable: true
  34789. });
  34790. Object.defineProperty(Material, "LineListDrawMode", {
  34791. /**
  34792. * Returns the line list draw mode
  34793. */
  34794. get: function () {
  34795. return Material._LineListDrawMode;
  34796. },
  34797. enumerable: true,
  34798. configurable: true
  34799. });
  34800. Object.defineProperty(Material, "LineLoopDrawMode", {
  34801. /**
  34802. * Returns the line loop draw mode
  34803. */
  34804. get: function () {
  34805. return Material._LineLoopDrawMode;
  34806. },
  34807. enumerable: true,
  34808. configurable: true
  34809. });
  34810. Object.defineProperty(Material, "LineStripDrawMode", {
  34811. /**
  34812. * Returns the line strip draw mode
  34813. */
  34814. get: function () {
  34815. return Material._LineStripDrawMode;
  34816. },
  34817. enumerable: true,
  34818. configurable: true
  34819. });
  34820. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34821. /**
  34822. * Returns the triangle strip draw mode
  34823. */
  34824. get: function () {
  34825. return Material._TriangleStripDrawMode;
  34826. },
  34827. enumerable: true,
  34828. configurable: true
  34829. });
  34830. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34831. /**
  34832. * Returns the triangle fan draw mode
  34833. */
  34834. get: function () {
  34835. return Material._TriangleFanDrawMode;
  34836. },
  34837. enumerable: true,
  34838. configurable: true
  34839. });
  34840. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34841. /**
  34842. * Returns the clock-wise side orientation
  34843. */
  34844. get: function () {
  34845. return Material._ClockWiseSideOrientation;
  34846. },
  34847. enumerable: true,
  34848. configurable: true
  34849. });
  34850. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34851. /**
  34852. * Returns the counter clock-wise side orientation
  34853. */
  34854. get: function () {
  34855. return Material._CounterClockWiseSideOrientation;
  34856. },
  34857. enumerable: true,
  34858. configurable: true
  34859. });
  34860. Object.defineProperty(Material, "TextureDirtyFlag", {
  34861. /**
  34862. * Returns the dirty texture flag value
  34863. */
  34864. get: function () {
  34865. return Material._TextureDirtyFlag;
  34866. },
  34867. enumerable: true,
  34868. configurable: true
  34869. });
  34870. Object.defineProperty(Material, "LightDirtyFlag", {
  34871. /**
  34872. * Returns the dirty light flag value
  34873. */
  34874. get: function () {
  34875. return Material._LightDirtyFlag;
  34876. },
  34877. enumerable: true,
  34878. configurable: true
  34879. });
  34880. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34881. /**
  34882. * Returns the dirty fresnel flag value
  34883. */
  34884. get: function () {
  34885. return Material._FresnelDirtyFlag;
  34886. },
  34887. enumerable: true,
  34888. configurable: true
  34889. });
  34890. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34891. /**
  34892. * Returns the dirty attributes flag value
  34893. */
  34894. get: function () {
  34895. return Material._AttributesDirtyFlag;
  34896. },
  34897. enumerable: true,
  34898. configurable: true
  34899. });
  34900. Object.defineProperty(Material, "MiscDirtyFlag", {
  34901. /**
  34902. * Returns the dirty misc flag value
  34903. */
  34904. get: function () {
  34905. return Material._MiscDirtyFlag;
  34906. },
  34907. enumerable: true,
  34908. configurable: true
  34909. });
  34910. Object.defineProperty(Material.prototype, "alpha", {
  34911. /**
  34912. * Gets the alpha value of the material
  34913. */
  34914. get: function () {
  34915. return this._alpha;
  34916. },
  34917. /**
  34918. * Sets the alpha value of the material
  34919. */
  34920. set: function (value) {
  34921. if (this._alpha === value) {
  34922. return;
  34923. }
  34924. this._alpha = value;
  34925. this.markAsDirty(Material.MiscDirtyFlag);
  34926. },
  34927. enumerable: true,
  34928. configurable: true
  34929. });
  34930. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34931. /**
  34932. * Gets the back-face culling state
  34933. */
  34934. get: function () {
  34935. return this._backFaceCulling;
  34936. },
  34937. /**
  34938. * Sets the back-face culling state
  34939. */
  34940. set: function (value) {
  34941. if (this._backFaceCulling === value) {
  34942. return;
  34943. }
  34944. this._backFaceCulling = value;
  34945. this.markAsDirty(Material.TextureDirtyFlag);
  34946. },
  34947. enumerable: true,
  34948. configurable: true
  34949. });
  34950. Object.defineProperty(Material.prototype, "onDispose", {
  34951. /**
  34952. * Called during a dispose event
  34953. */
  34954. set: function (callback) {
  34955. if (this._onDisposeObserver) {
  34956. this.onDisposeObservable.remove(this._onDisposeObserver);
  34957. }
  34958. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34959. },
  34960. enumerable: true,
  34961. configurable: true
  34962. });
  34963. Object.defineProperty(Material.prototype, "onBindObservable", {
  34964. /**
  34965. * An event triggered when the material is bound
  34966. */
  34967. get: function () {
  34968. if (!this._onBindObservable) {
  34969. this._onBindObservable = new BABYLON.Observable();
  34970. }
  34971. return this._onBindObservable;
  34972. },
  34973. enumerable: true,
  34974. configurable: true
  34975. });
  34976. Object.defineProperty(Material.prototype, "onBind", {
  34977. /**
  34978. * Called during a bind event
  34979. */
  34980. set: function (callback) {
  34981. if (this._onBindObserver) {
  34982. this.onBindObservable.remove(this._onBindObserver);
  34983. }
  34984. this._onBindObserver = this.onBindObservable.add(callback);
  34985. },
  34986. enumerable: true,
  34987. configurable: true
  34988. });
  34989. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34990. /**
  34991. * An event triggered when the material is unbound
  34992. */
  34993. get: function () {
  34994. if (!this._onUnBindObservable) {
  34995. this._onUnBindObservable = new BABYLON.Observable();
  34996. }
  34997. return this._onUnBindObservable;
  34998. },
  34999. enumerable: true,
  35000. configurable: true
  35001. });
  35002. Object.defineProperty(Material.prototype, "alphaMode", {
  35003. /**
  35004. * Gets the value of the alpha mode
  35005. */
  35006. get: function () {
  35007. return this._alphaMode;
  35008. },
  35009. /**
  35010. * Sets the value of the alpha mode.
  35011. *
  35012. * | Value | Type | Description |
  35013. * | --- | --- | --- |
  35014. * | 0 | ALPHA_DISABLE | |
  35015. * | 1 | ALPHA_ADD | |
  35016. * | 2 | ALPHA_COMBINE | |
  35017. * | 3 | ALPHA_SUBTRACT | |
  35018. * | 4 | ALPHA_MULTIPLY | |
  35019. * | 5 | ALPHA_MAXIMIZED | |
  35020. * | 6 | ALPHA_ONEONE | |
  35021. * | 7 | ALPHA_PREMULTIPLIED | |
  35022. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35023. * | 9 | ALPHA_INTERPOLATE | |
  35024. * | 10 | ALPHA_SCREENMODE | |
  35025. *
  35026. */
  35027. set: function (value) {
  35028. if (this._alphaMode === value) {
  35029. return;
  35030. }
  35031. this._alphaMode = value;
  35032. this.markAsDirty(Material.TextureDirtyFlag);
  35033. },
  35034. enumerable: true,
  35035. configurable: true
  35036. });
  35037. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35038. /**
  35039. * Gets the depth pre-pass value
  35040. */
  35041. get: function () {
  35042. return this._needDepthPrePass;
  35043. },
  35044. /**
  35045. * Sets the need depth pre-pass value
  35046. */
  35047. set: function (value) {
  35048. if (this._needDepthPrePass === value) {
  35049. return;
  35050. }
  35051. this._needDepthPrePass = value;
  35052. if (this._needDepthPrePass) {
  35053. this.checkReadyOnEveryCall = true;
  35054. }
  35055. },
  35056. enumerable: true,
  35057. configurable: true
  35058. });
  35059. Object.defineProperty(Material.prototype, "fogEnabled", {
  35060. /**
  35061. * Gets the value of the fog enabled state
  35062. */
  35063. get: function () {
  35064. return this._fogEnabled;
  35065. },
  35066. /**
  35067. * Sets the state for enabling fog
  35068. */
  35069. set: function (value) {
  35070. if (this._fogEnabled === value) {
  35071. return;
  35072. }
  35073. this._fogEnabled = value;
  35074. this.markAsDirty(Material.MiscDirtyFlag);
  35075. },
  35076. enumerable: true,
  35077. configurable: true
  35078. });
  35079. Object.defineProperty(Material.prototype, "wireframe", {
  35080. /**
  35081. * Gets a value specifying if wireframe mode is enabled
  35082. */
  35083. get: function () {
  35084. switch (this._fillMode) {
  35085. case Material.WireFrameFillMode:
  35086. case Material.LineListDrawMode:
  35087. case Material.LineLoopDrawMode:
  35088. case Material.LineStripDrawMode:
  35089. return true;
  35090. }
  35091. return this._scene.forceWireframe;
  35092. },
  35093. /**
  35094. * Sets the state of wireframe mode
  35095. */
  35096. set: function (value) {
  35097. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35098. },
  35099. enumerable: true,
  35100. configurable: true
  35101. });
  35102. Object.defineProperty(Material.prototype, "pointsCloud", {
  35103. /**
  35104. * Gets the value specifying if point clouds are enabled
  35105. */
  35106. get: function () {
  35107. switch (this._fillMode) {
  35108. case Material.PointFillMode:
  35109. case Material.PointListDrawMode:
  35110. return true;
  35111. }
  35112. return this._scene.forcePointsCloud;
  35113. },
  35114. /**
  35115. * Sets the state of point cloud mode
  35116. */
  35117. set: function (value) {
  35118. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35119. },
  35120. enumerable: true,
  35121. configurable: true
  35122. });
  35123. Object.defineProperty(Material.prototype, "fillMode", {
  35124. /**
  35125. * Gets the material fill mode
  35126. */
  35127. get: function () {
  35128. return this._fillMode;
  35129. },
  35130. /**
  35131. * Sets the material fill mode
  35132. */
  35133. set: function (value) {
  35134. if (this._fillMode === value) {
  35135. return;
  35136. }
  35137. this._fillMode = value;
  35138. this.markAsDirty(Material.MiscDirtyFlag);
  35139. },
  35140. enumerable: true,
  35141. configurable: true
  35142. });
  35143. /**
  35144. * Returns a string representation of the current material
  35145. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35146. * @returns a string with material information
  35147. */
  35148. Material.prototype.toString = function (fullDetails) {
  35149. var ret = "Name: " + this.name;
  35150. if (fullDetails) {
  35151. }
  35152. return ret;
  35153. };
  35154. /**
  35155. * Gets the class name of the material
  35156. * @returns a string with the class name of the material
  35157. */
  35158. Material.prototype.getClassName = function () {
  35159. return "Material";
  35160. };
  35161. Object.defineProperty(Material.prototype, "isFrozen", {
  35162. /**
  35163. * Specifies if updates for the material been locked
  35164. */
  35165. get: function () {
  35166. return this.checkReadyOnlyOnce;
  35167. },
  35168. enumerable: true,
  35169. configurable: true
  35170. });
  35171. /**
  35172. * Locks updates for the material
  35173. */
  35174. Material.prototype.freeze = function () {
  35175. this.checkReadyOnlyOnce = true;
  35176. };
  35177. /**
  35178. * Unlocks updates for the material
  35179. */
  35180. Material.prototype.unfreeze = function () {
  35181. this.checkReadyOnlyOnce = false;
  35182. };
  35183. /**
  35184. * Specifies if the material is ready to be used
  35185. * @param mesh defines the mesh to check
  35186. * @param useInstances specifies if instances should be used
  35187. * @returns a boolean indicating if the material is ready to be used
  35188. */
  35189. Material.prototype.isReady = function (mesh, useInstances) {
  35190. return true;
  35191. };
  35192. /**
  35193. * Specifies that the submesh is ready to be used
  35194. * @param mesh defines the mesh to check
  35195. * @param subMesh defines which submesh to check
  35196. * @param useInstances specifies that instances should be used
  35197. * @returns a boolean indicating that the submesh is ready or not
  35198. */
  35199. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35200. return false;
  35201. };
  35202. /**
  35203. * Returns the material effect
  35204. * @returns the effect associated with the material
  35205. */
  35206. Material.prototype.getEffect = function () {
  35207. return this._effect;
  35208. };
  35209. /**
  35210. * Returns the current scene
  35211. * @returns a Scene
  35212. */
  35213. Material.prototype.getScene = function () {
  35214. return this._scene;
  35215. };
  35216. /**
  35217. * Specifies if the material will require alpha blending
  35218. * @returns a boolean specifying if alpha blending is needed
  35219. */
  35220. Material.prototype.needAlphaBlending = function () {
  35221. return (this.alpha < 1.0);
  35222. };
  35223. /**
  35224. * Specifies if the mesh will require alpha blending
  35225. * @param mesh defines the mesh to check
  35226. * @returns a boolean specifying if alpha blending is needed for the mesh
  35227. */
  35228. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35229. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35230. };
  35231. /**
  35232. * Specifies if this material should be rendered in alpha test mode
  35233. * @returns a boolean specifying if an alpha test is needed.
  35234. */
  35235. Material.prototype.needAlphaTesting = function () {
  35236. return false;
  35237. };
  35238. /**
  35239. * Gets the texture used for the alpha test
  35240. * @returns the texture to use for alpha testing
  35241. */
  35242. Material.prototype.getAlphaTestTexture = function () {
  35243. return null;
  35244. };
  35245. /**
  35246. * Marks the material to indicate that it needs to be re-calculated
  35247. */
  35248. Material.prototype.markDirty = function () {
  35249. this._wasPreviouslyReady = false;
  35250. };
  35251. /** @hidden */
  35252. Material.prototype._preBind = function (effect, overrideOrientation) {
  35253. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35254. var engine = this._scene.getEngine();
  35255. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35256. var reverse = orientation === Material.ClockWiseSideOrientation;
  35257. engine.enableEffect(effect ? effect : this._effect);
  35258. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35259. return reverse;
  35260. };
  35261. /**
  35262. * Binds the material to the mesh
  35263. * @param world defines the world transformation matrix
  35264. * @param mesh defines the mesh to bind the material to
  35265. */
  35266. Material.prototype.bind = function (world, mesh) {
  35267. };
  35268. /**
  35269. * Binds the submesh to the material
  35270. * @param world defines the world transformation matrix
  35271. * @param mesh defines the mesh containing the submesh
  35272. * @param subMesh defines the submesh to bind the material to
  35273. */
  35274. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35275. };
  35276. /**
  35277. * Binds the world matrix to the material
  35278. * @param world defines the world transformation matrix
  35279. */
  35280. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35281. };
  35282. /**
  35283. * Binds the scene's uniform buffer to the effect.
  35284. * @param effect defines the effect to bind to the scene uniform buffer
  35285. * @param sceneUbo defines the uniform buffer storing scene data
  35286. */
  35287. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35288. sceneUbo.bindToEffect(effect, "Scene");
  35289. };
  35290. /**
  35291. * Binds the view matrix to the effect
  35292. * @param effect defines the effect to bind the view matrix to
  35293. */
  35294. Material.prototype.bindView = function (effect) {
  35295. if (!this._useUBO) {
  35296. effect.setMatrix("view", this.getScene().getViewMatrix());
  35297. }
  35298. else {
  35299. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35300. }
  35301. };
  35302. /**
  35303. * Binds the view projection matrix to the effect
  35304. * @param effect defines the effect to bind the view projection matrix to
  35305. */
  35306. Material.prototype.bindViewProjection = function (effect) {
  35307. if (!this._useUBO) {
  35308. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35309. }
  35310. else {
  35311. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35312. }
  35313. };
  35314. /**
  35315. * Specifies if material alpha testing should be turned on for the mesh
  35316. * @param mesh defines the mesh to check
  35317. */
  35318. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35319. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35320. };
  35321. /**
  35322. * Processes to execute after binding the material to a mesh
  35323. * @param mesh defines the rendered mesh
  35324. */
  35325. Material.prototype._afterBind = function (mesh) {
  35326. this._scene._cachedMaterial = this;
  35327. if (mesh) {
  35328. this._scene._cachedVisibility = mesh.visibility;
  35329. }
  35330. else {
  35331. this._scene._cachedVisibility = 1;
  35332. }
  35333. if (this._onBindObservable && mesh) {
  35334. this._onBindObservable.notifyObservers(mesh);
  35335. }
  35336. if (this.disableDepthWrite) {
  35337. var engine = this._scene.getEngine();
  35338. this._cachedDepthWriteState = engine.getDepthWrite();
  35339. engine.setDepthWrite(false);
  35340. }
  35341. };
  35342. /**
  35343. * Unbinds the material from the mesh
  35344. */
  35345. Material.prototype.unbind = function () {
  35346. if (this._onUnBindObservable) {
  35347. this._onUnBindObservable.notifyObservers(this);
  35348. }
  35349. if (this.disableDepthWrite) {
  35350. var engine = this._scene.getEngine();
  35351. engine.setDepthWrite(this._cachedDepthWriteState);
  35352. }
  35353. };
  35354. /**
  35355. * Gets the active textures from the material
  35356. * @returns an array of textures
  35357. */
  35358. Material.prototype.getActiveTextures = function () {
  35359. return [];
  35360. };
  35361. /**
  35362. * Specifies if the material uses a texture
  35363. * @param texture defines the texture to check against the material
  35364. * @returns a boolean specifying if the material uses the texture
  35365. */
  35366. Material.prototype.hasTexture = function (texture) {
  35367. return false;
  35368. };
  35369. /**
  35370. * Makes a duplicate of the material, and gives it a new name
  35371. * @param name defines the new name for the duplicated material
  35372. * @returns the cloned material
  35373. */
  35374. Material.prototype.clone = function (name) {
  35375. return null;
  35376. };
  35377. /**
  35378. * Gets the meshes bound to the material
  35379. * @returns an array of meshes bound to the material
  35380. */
  35381. Material.prototype.getBindedMeshes = function () {
  35382. var result = new Array();
  35383. for (var index = 0; index < this._scene.meshes.length; index++) {
  35384. var mesh = this._scene.meshes[index];
  35385. if (mesh.material === this) {
  35386. result.push(mesh);
  35387. }
  35388. }
  35389. return result;
  35390. };
  35391. /**
  35392. * Force shader compilation
  35393. * @param mesh defines the mesh associated with this material
  35394. * @param onCompiled defines a function to execute once the material is compiled
  35395. * @param options defines the options to configure the compilation
  35396. */
  35397. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35398. var _this = this;
  35399. var localOptions = __assign({ clipPlane: false }, options);
  35400. var subMesh = new BABYLON.BaseSubMesh();
  35401. var scene = this.getScene();
  35402. var checkReady = function () {
  35403. if (!_this._scene || !_this._scene.getEngine()) {
  35404. return;
  35405. }
  35406. if (subMesh._materialDefines) {
  35407. subMesh._materialDefines._renderId = -1;
  35408. }
  35409. var clipPlaneState = scene.clipPlane;
  35410. if (localOptions.clipPlane) {
  35411. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35412. }
  35413. if (_this.storeEffectOnSubMeshes) {
  35414. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35415. if (onCompiled) {
  35416. onCompiled(_this);
  35417. }
  35418. }
  35419. else {
  35420. setTimeout(checkReady, 16);
  35421. }
  35422. }
  35423. else {
  35424. if (_this.isReady(mesh)) {
  35425. if (onCompiled) {
  35426. onCompiled(_this);
  35427. }
  35428. }
  35429. else {
  35430. setTimeout(checkReady, 16);
  35431. }
  35432. }
  35433. if (localOptions.clipPlane) {
  35434. scene.clipPlane = clipPlaneState;
  35435. }
  35436. };
  35437. checkReady();
  35438. };
  35439. /**
  35440. * Force shader compilation
  35441. * @param mesh defines the mesh that will use this material
  35442. * @param options defines additional options for compiling the shaders
  35443. * @returns a promise that resolves when the compilation completes
  35444. */
  35445. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35446. var _this = this;
  35447. return new Promise(function (resolve) {
  35448. _this.forceCompilation(mesh, function () {
  35449. resolve();
  35450. }, options);
  35451. });
  35452. };
  35453. /**
  35454. * Marks a define in the material to indicate that it needs to be re-computed
  35455. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35456. */
  35457. Material.prototype.markAsDirty = function (flag) {
  35458. if (flag & Material.TextureDirtyFlag) {
  35459. this._markAllSubMeshesAsTexturesDirty();
  35460. }
  35461. if (flag & Material.LightDirtyFlag) {
  35462. this._markAllSubMeshesAsLightsDirty();
  35463. }
  35464. if (flag & Material.FresnelDirtyFlag) {
  35465. this._markAllSubMeshesAsFresnelDirty();
  35466. }
  35467. if (flag & Material.AttributesDirtyFlag) {
  35468. this._markAllSubMeshesAsAttributesDirty();
  35469. }
  35470. if (flag & Material.MiscDirtyFlag) {
  35471. this._markAllSubMeshesAsMiscDirty();
  35472. }
  35473. this.getScene().resetCachedMaterial();
  35474. };
  35475. /**
  35476. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35477. * @param func defines a function which checks material defines against the submeshes
  35478. */
  35479. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35480. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35481. var mesh = _a[_i];
  35482. if (!mesh.subMeshes) {
  35483. continue;
  35484. }
  35485. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35486. var subMesh = _c[_b];
  35487. if (subMesh.getMaterial() !== this) {
  35488. continue;
  35489. }
  35490. if (!subMesh._materialDefines) {
  35491. continue;
  35492. }
  35493. func(subMesh._materialDefines);
  35494. }
  35495. }
  35496. };
  35497. /**
  35498. * Indicates that image processing needs to be re-calculated for all submeshes
  35499. */
  35500. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35501. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35502. };
  35503. /**
  35504. * Indicates that textures need to be re-calculated for all submeshes
  35505. */
  35506. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35507. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35508. };
  35509. /**
  35510. * Indicates that fresnel needs to be re-calculated for all submeshes
  35511. */
  35512. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35513. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35514. };
  35515. /**
  35516. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35517. */
  35518. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35519. this._markAllSubMeshesAsDirty(function (defines) {
  35520. defines.markAsFresnelDirty();
  35521. defines.markAsMiscDirty();
  35522. });
  35523. };
  35524. /**
  35525. * Indicates that lights need to be re-calculated for all submeshes
  35526. */
  35527. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35528. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35529. };
  35530. /**
  35531. * Indicates that attributes need to be re-calculated for all submeshes
  35532. */
  35533. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35534. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35535. };
  35536. /**
  35537. * Indicates that misc needs to be re-calculated for all submeshes
  35538. */
  35539. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35540. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35541. };
  35542. /**
  35543. * Indicates that textures and misc need to be re-calculated for all submeshes
  35544. */
  35545. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35546. this._markAllSubMeshesAsDirty(function (defines) {
  35547. defines.markAsTexturesDirty();
  35548. defines.markAsMiscDirty();
  35549. });
  35550. };
  35551. /**
  35552. * Disposes the material
  35553. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35554. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35555. */
  35556. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35557. // Animations
  35558. this.getScene().stopAnimation(this);
  35559. this.getScene().freeProcessedMaterials();
  35560. // Remove from scene
  35561. var index = this._scene.materials.indexOf(this);
  35562. if (index >= 0) {
  35563. this._scene.materials.splice(index, 1);
  35564. }
  35565. // Remove from meshes
  35566. for (index = 0; index < this._scene.meshes.length; index++) {
  35567. var mesh = this._scene.meshes[index];
  35568. if (mesh.material === this) {
  35569. mesh.material = null;
  35570. if (mesh.geometry) {
  35571. var geometry = (mesh.geometry);
  35572. if (this.storeEffectOnSubMeshes) {
  35573. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35574. var subMesh = _a[_i];
  35575. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35576. if (forceDisposeEffect && subMesh._materialEffect) {
  35577. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35578. }
  35579. }
  35580. }
  35581. else {
  35582. geometry._releaseVertexArrayObject(this._effect);
  35583. }
  35584. }
  35585. }
  35586. }
  35587. this._uniformBuffer.dispose();
  35588. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35589. if (forceDisposeEffect && this._effect) {
  35590. if (!this.storeEffectOnSubMeshes) {
  35591. this._scene.getEngine()._releaseEffect(this._effect);
  35592. }
  35593. this._effect = null;
  35594. }
  35595. // Callback
  35596. this.onDisposeObservable.notifyObservers(this);
  35597. this.onDisposeObservable.clear();
  35598. if (this._onBindObservable) {
  35599. this._onBindObservable.clear();
  35600. }
  35601. if (this._onUnBindObservable) {
  35602. this._onUnBindObservable.clear();
  35603. }
  35604. };
  35605. /**
  35606. * Serializes this material
  35607. * @returns the serialized material object
  35608. */
  35609. Material.prototype.serialize = function () {
  35610. return BABYLON.SerializationHelper.Serialize(this);
  35611. };
  35612. /**
  35613. * Creates a MultiMaterial from parsed MultiMaterial data.
  35614. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35615. * @param scene defines the hosting scene
  35616. * @returns a new MultiMaterial
  35617. */
  35618. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35619. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35620. multiMaterial.id = parsedMultiMaterial.id;
  35621. if (BABYLON.Tags) {
  35622. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35623. }
  35624. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35625. var subMatId = parsedMultiMaterial.materials[matIndex];
  35626. if (subMatId) {
  35627. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35628. }
  35629. else {
  35630. multiMaterial.subMaterials.push(null);
  35631. }
  35632. }
  35633. return multiMaterial;
  35634. };
  35635. /**
  35636. * Creates a material from parsed material data
  35637. * @param parsedMaterial defines parsed material data
  35638. * @param scene defines the hosting scene
  35639. * @param rootUrl defines the root URL to use to load textures
  35640. * @returns a new material
  35641. */
  35642. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35643. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35644. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35645. }
  35646. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35647. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35648. if (!BABYLON.LegacyPBRMaterial) {
  35649. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35650. return;
  35651. }
  35652. }
  35653. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35654. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35655. };
  35656. // Triangle views
  35657. Material._TriangleFillMode = 0;
  35658. Material._WireFrameFillMode = 1;
  35659. Material._PointFillMode = 2;
  35660. // Draw modes
  35661. Material._PointListDrawMode = 3;
  35662. Material._LineListDrawMode = 4;
  35663. Material._LineLoopDrawMode = 5;
  35664. Material._LineStripDrawMode = 6;
  35665. Material._TriangleStripDrawMode = 7;
  35666. Material._TriangleFanDrawMode = 8;
  35667. /**
  35668. * Stores the clock-wise side orientation
  35669. */
  35670. Material._ClockWiseSideOrientation = 0;
  35671. /**
  35672. * Stores the counter clock-wise side orientation
  35673. */
  35674. Material._CounterClockWiseSideOrientation = 1;
  35675. /**
  35676. * The dirty texture flag value
  35677. */
  35678. Material._TextureDirtyFlag = 1;
  35679. /**
  35680. * The dirty light flag value
  35681. */
  35682. Material._LightDirtyFlag = 2;
  35683. /**
  35684. * The dirty fresnel flag value
  35685. */
  35686. Material._FresnelDirtyFlag = 4;
  35687. /**
  35688. * The dirty attribute flag value
  35689. */
  35690. Material._AttributesDirtyFlag = 8;
  35691. /**
  35692. * The dirty misc flag value
  35693. */
  35694. Material._MiscDirtyFlag = 16;
  35695. __decorate([
  35696. BABYLON.serialize()
  35697. ], Material.prototype, "id", void 0);
  35698. __decorate([
  35699. BABYLON.serialize()
  35700. ], Material.prototype, "uniqueId", void 0);
  35701. __decorate([
  35702. BABYLON.serialize()
  35703. ], Material.prototype, "name", void 0);
  35704. __decorate([
  35705. BABYLON.serialize()
  35706. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35707. __decorate([
  35708. BABYLON.serialize()
  35709. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35710. __decorate([
  35711. BABYLON.serialize()
  35712. ], Material.prototype, "state", void 0);
  35713. __decorate([
  35714. BABYLON.serialize("alpha")
  35715. ], Material.prototype, "_alpha", void 0);
  35716. __decorate([
  35717. BABYLON.serialize("backFaceCulling")
  35718. ], Material.prototype, "_backFaceCulling", void 0);
  35719. __decorate([
  35720. BABYLON.serialize()
  35721. ], Material.prototype, "sideOrientation", void 0);
  35722. __decorate([
  35723. BABYLON.serialize("alphaMode")
  35724. ], Material.prototype, "_alphaMode", void 0);
  35725. __decorate([
  35726. BABYLON.serialize()
  35727. ], Material.prototype, "_needDepthPrePass", void 0);
  35728. __decorate([
  35729. BABYLON.serialize()
  35730. ], Material.prototype, "disableDepthWrite", void 0);
  35731. __decorate([
  35732. BABYLON.serialize()
  35733. ], Material.prototype, "forceDepthWrite", void 0);
  35734. __decorate([
  35735. BABYLON.serialize()
  35736. ], Material.prototype, "separateCullingPass", void 0);
  35737. __decorate([
  35738. BABYLON.serialize("fogEnabled")
  35739. ], Material.prototype, "_fogEnabled", void 0);
  35740. __decorate([
  35741. BABYLON.serialize()
  35742. ], Material.prototype, "pointSize", void 0);
  35743. __decorate([
  35744. BABYLON.serialize()
  35745. ], Material.prototype, "zOffset", void 0);
  35746. __decorate([
  35747. BABYLON.serialize()
  35748. ], Material.prototype, "wireframe", null);
  35749. __decorate([
  35750. BABYLON.serialize()
  35751. ], Material.prototype, "pointsCloud", null);
  35752. __decorate([
  35753. BABYLON.serialize()
  35754. ], Material.prototype, "fillMode", null);
  35755. return Material;
  35756. }());
  35757. BABYLON.Material = Material;
  35758. })(BABYLON || (BABYLON = {}));
  35759. //# sourceMappingURL=babylon.material.js.map
  35760. var BABYLON;
  35761. (function (BABYLON) {
  35762. var UniformBuffer = /** @class */ (function () {
  35763. /**
  35764. * Uniform buffer objects.
  35765. *
  35766. * Handles blocks of uniform on the GPU.
  35767. *
  35768. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35769. *
  35770. * For more information, please refer to :
  35771. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35772. */
  35773. function UniformBuffer(engine, data, dynamic) {
  35774. this._engine = engine;
  35775. this._noUBO = !engine.supportsUniformBuffers;
  35776. this._dynamic = dynamic;
  35777. this._data = data || [];
  35778. this._uniformLocations = {};
  35779. this._uniformSizes = {};
  35780. this._uniformLocationPointer = 0;
  35781. this._needSync = false;
  35782. if (this._noUBO) {
  35783. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35784. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35785. this.updateFloat = this._updateFloatForEffect;
  35786. this.updateFloat2 = this._updateFloat2ForEffect;
  35787. this.updateFloat3 = this._updateFloat3ForEffect;
  35788. this.updateFloat4 = this._updateFloat4ForEffect;
  35789. this.updateMatrix = this._updateMatrixForEffect;
  35790. this.updateVector3 = this._updateVector3ForEffect;
  35791. this.updateVector4 = this._updateVector4ForEffect;
  35792. this.updateColor3 = this._updateColor3ForEffect;
  35793. this.updateColor4 = this._updateColor4ForEffect;
  35794. }
  35795. else {
  35796. this._engine._uniformBuffers.push(this);
  35797. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35798. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35799. this.updateFloat = this._updateFloatForUniform;
  35800. this.updateFloat2 = this._updateFloat2ForUniform;
  35801. this.updateFloat3 = this._updateFloat3ForUniform;
  35802. this.updateFloat4 = this._updateFloat4ForUniform;
  35803. this.updateMatrix = this._updateMatrixForUniform;
  35804. this.updateVector3 = this._updateVector3ForUniform;
  35805. this.updateVector4 = this._updateVector4ForUniform;
  35806. this.updateColor3 = this._updateColor3ForUniform;
  35807. this.updateColor4 = this._updateColor4ForUniform;
  35808. }
  35809. }
  35810. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35811. // Properties
  35812. /**
  35813. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35814. * or just falling back on setUniformXXX calls.
  35815. */
  35816. get: function () {
  35817. return !this._noUBO;
  35818. },
  35819. enumerable: true,
  35820. configurable: true
  35821. });
  35822. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35823. /**
  35824. * Indicates if the WebGL underlying uniform buffer is in sync
  35825. * with the javascript cache data.
  35826. */
  35827. get: function () {
  35828. return !this._needSync;
  35829. },
  35830. enumerable: true,
  35831. configurable: true
  35832. });
  35833. /**
  35834. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35835. * Also, a dynamic UniformBuffer will disable cache verification and always
  35836. * update the underlying WebGL uniform buffer to the GPU.
  35837. */
  35838. UniformBuffer.prototype.isDynamic = function () {
  35839. return this._dynamic !== undefined;
  35840. };
  35841. /**
  35842. * The data cache on JS side.
  35843. */
  35844. UniformBuffer.prototype.getData = function () {
  35845. return this._bufferData;
  35846. };
  35847. /**
  35848. * The underlying WebGL Uniform buffer.
  35849. */
  35850. UniformBuffer.prototype.getBuffer = function () {
  35851. return this._buffer;
  35852. };
  35853. /**
  35854. * std140 layout specifies how to align data within an UBO structure.
  35855. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35856. * for specs.
  35857. */
  35858. UniformBuffer.prototype._fillAlignment = function (size) {
  35859. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35860. // and 4x4 matrices
  35861. // TODO : change if other types are used
  35862. var alignment;
  35863. if (size <= 2) {
  35864. alignment = size;
  35865. }
  35866. else {
  35867. alignment = 4;
  35868. }
  35869. if ((this._uniformLocationPointer % alignment) !== 0) {
  35870. var oldPointer = this._uniformLocationPointer;
  35871. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35872. var diff = this._uniformLocationPointer - oldPointer;
  35873. for (var i = 0; i < diff; i++) {
  35874. this._data.push(0);
  35875. }
  35876. }
  35877. };
  35878. /**
  35879. * Adds an uniform in the buffer.
  35880. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35881. * for the layout to be correct !
  35882. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35883. * @param {number|number[]} size Data size, or data directly.
  35884. */
  35885. UniformBuffer.prototype.addUniform = function (name, size) {
  35886. if (this._noUBO) {
  35887. return;
  35888. }
  35889. if (this._uniformLocations[name] !== undefined) {
  35890. // Already existing uniform
  35891. return;
  35892. }
  35893. // This function must be called in the order of the shader layout !
  35894. // size can be the size of the uniform, or data directly
  35895. var data;
  35896. if (size instanceof Array) {
  35897. data = size;
  35898. size = data.length;
  35899. }
  35900. else {
  35901. size = size;
  35902. data = [];
  35903. // Fill with zeros
  35904. for (var i = 0; i < size; i++) {
  35905. data.push(0);
  35906. }
  35907. }
  35908. this._fillAlignment(size);
  35909. this._uniformSizes[name] = size;
  35910. this._uniformLocations[name] = this._uniformLocationPointer;
  35911. this._uniformLocationPointer += size;
  35912. for (var i = 0; i < size; i++) {
  35913. this._data.push(data[i]);
  35914. }
  35915. this._needSync = true;
  35916. };
  35917. /**
  35918. * Wrapper for addUniform.
  35919. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35920. * @param {Matrix} mat A 4x4 matrix.
  35921. */
  35922. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35923. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35924. };
  35925. /**
  35926. * Wrapper for addUniform.
  35927. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35928. * @param {number} x
  35929. * @param {number} y
  35930. */
  35931. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35932. var temp = [x, y];
  35933. this.addUniform(name, temp);
  35934. };
  35935. /**
  35936. * Wrapper for addUniform.
  35937. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35938. * @param {number} x
  35939. * @param {number} y
  35940. * @param {number} z
  35941. */
  35942. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35943. var temp = [x, y, z];
  35944. this.addUniform(name, temp);
  35945. };
  35946. /**
  35947. * Wrapper for addUniform.
  35948. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35949. * @param {Color3} color
  35950. */
  35951. UniformBuffer.prototype.addColor3 = function (name, color) {
  35952. var temp = new Array();
  35953. color.toArray(temp);
  35954. this.addUniform(name, temp);
  35955. };
  35956. /**
  35957. * Wrapper for addUniform.
  35958. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35959. * @param {Color3} color
  35960. * @param {number} alpha
  35961. */
  35962. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35963. var temp = new Array();
  35964. color.toArray(temp);
  35965. temp.push(alpha);
  35966. this.addUniform(name, temp);
  35967. };
  35968. /**
  35969. * Wrapper for addUniform.
  35970. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35971. * @param {Vector3} vector
  35972. */
  35973. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35974. var temp = new Array();
  35975. vector.toArray(temp);
  35976. this.addUniform(name, temp);
  35977. };
  35978. /**
  35979. * Wrapper for addUniform.
  35980. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35981. */
  35982. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35983. this.addUniform(name, 12);
  35984. };
  35985. /**
  35986. * Wrapper for addUniform.
  35987. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35988. */
  35989. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35990. this.addUniform(name, 8);
  35991. };
  35992. /**
  35993. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35994. */
  35995. UniformBuffer.prototype.create = function () {
  35996. if (this._noUBO) {
  35997. return;
  35998. }
  35999. if (this._buffer) {
  36000. return; // nothing to do
  36001. }
  36002. // See spec, alignment must be filled as a vec4
  36003. this._fillAlignment(4);
  36004. this._bufferData = new Float32Array(this._data);
  36005. this._rebuild();
  36006. this._needSync = true;
  36007. };
  36008. /** @hidden */
  36009. UniformBuffer.prototype._rebuild = function () {
  36010. if (this._noUBO) {
  36011. return;
  36012. }
  36013. if (this._dynamic) {
  36014. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36015. }
  36016. else {
  36017. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36018. }
  36019. };
  36020. /**
  36021. * Updates the WebGL Uniform Buffer on the GPU.
  36022. * If the `dynamic` flag is set to true, no cache comparison is done.
  36023. * Otherwise, the buffer will be updated only if the cache differs.
  36024. */
  36025. UniformBuffer.prototype.update = function () {
  36026. if (!this._buffer) {
  36027. this.create();
  36028. return;
  36029. }
  36030. if (!this._dynamic && !this._needSync) {
  36031. return;
  36032. }
  36033. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36034. this._needSync = false;
  36035. };
  36036. /**
  36037. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36038. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36039. * @param {number[]|Float32Array} data Flattened data
  36040. * @param {number} size Size of the data.
  36041. */
  36042. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36043. var location = this._uniformLocations[uniformName];
  36044. if (location === undefined) {
  36045. if (this._buffer) {
  36046. // Cannot add an uniform if the buffer is already created
  36047. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36048. return;
  36049. }
  36050. this.addUniform(uniformName, size);
  36051. location = this._uniformLocations[uniformName];
  36052. }
  36053. if (!this._buffer) {
  36054. this.create();
  36055. }
  36056. if (!this._dynamic) {
  36057. // Cache for static uniform buffers
  36058. var changed = false;
  36059. for (var i = 0; i < size; i++) {
  36060. if (this._bufferData[location + i] !== data[i]) {
  36061. changed = true;
  36062. this._bufferData[location + i] = data[i];
  36063. }
  36064. }
  36065. this._needSync = this._needSync || changed;
  36066. }
  36067. else {
  36068. // No cache for dynamic
  36069. for (var i = 0; i < size; i++) {
  36070. this._bufferData[location + i] = data[i];
  36071. }
  36072. }
  36073. };
  36074. // Update methods
  36075. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36076. // To match std140, matrix must be realigned
  36077. for (var i = 0; i < 3; i++) {
  36078. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36079. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36080. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36081. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36082. }
  36083. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36084. };
  36085. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36086. this._currentEffect.setMatrix3x3(name, matrix);
  36087. };
  36088. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36089. this._currentEffect.setMatrix2x2(name, matrix);
  36090. };
  36091. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36092. // To match std140, matrix must be realigned
  36093. for (var i = 0; i < 2; i++) {
  36094. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36095. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36096. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36097. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36098. }
  36099. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36100. };
  36101. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36102. this._currentEffect.setFloat(name, x);
  36103. };
  36104. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36105. UniformBuffer._tempBuffer[0] = x;
  36106. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36107. };
  36108. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36109. if (suffix === void 0) { suffix = ""; }
  36110. this._currentEffect.setFloat2(name + suffix, x, y);
  36111. };
  36112. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36113. if (suffix === void 0) { suffix = ""; }
  36114. UniformBuffer._tempBuffer[0] = x;
  36115. UniformBuffer._tempBuffer[1] = y;
  36116. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36117. };
  36118. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36119. if (suffix === void 0) { suffix = ""; }
  36120. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36121. };
  36122. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36123. if (suffix === void 0) { suffix = ""; }
  36124. UniformBuffer._tempBuffer[0] = x;
  36125. UniformBuffer._tempBuffer[1] = y;
  36126. UniformBuffer._tempBuffer[2] = z;
  36127. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36128. };
  36129. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36130. if (suffix === void 0) { suffix = ""; }
  36131. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36132. };
  36133. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36134. if (suffix === void 0) { suffix = ""; }
  36135. UniformBuffer._tempBuffer[0] = x;
  36136. UniformBuffer._tempBuffer[1] = y;
  36137. UniformBuffer._tempBuffer[2] = z;
  36138. UniformBuffer._tempBuffer[3] = w;
  36139. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36140. };
  36141. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36142. this._currentEffect.setMatrix(name, mat);
  36143. };
  36144. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36145. this.updateUniform(name, mat.toArray(), 16);
  36146. };
  36147. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36148. this._currentEffect.setVector3(name, vector);
  36149. };
  36150. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36151. vector.toArray(UniformBuffer._tempBuffer);
  36152. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36153. };
  36154. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36155. this._currentEffect.setVector4(name, vector);
  36156. };
  36157. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36158. vector.toArray(UniformBuffer._tempBuffer);
  36159. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36160. };
  36161. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36162. if (suffix === void 0) { suffix = ""; }
  36163. this._currentEffect.setColor3(name + suffix, color);
  36164. };
  36165. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36166. if (suffix === void 0) { suffix = ""; }
  36167. color.toArray(UniformBuffer._tempBuffer);
  36168. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36169. };
  36170. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36171. if (suffix === void 0) { suffix = ""; }
  36172. this._currentEffect.setColor4(name + suffix, color, alpha);
  36173. };
  36174. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36175. if (suffix === void 0) { suffix = ""; }
  36176. color.toArray(UniformBuffer._tempBuffer);
  36177. UniformBuffer._tempBuffer[3] = alpha;
  36178. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36179. };
  36180. /**
  36181. * Sets a sampler uniform on the effect.
  36182. * @param {string} name Name of the sampler.
  36183. * @param {Texture} texture
  36184. */
  36185. UniformBuffer.prototype.setTexture = function (name, texture) {
  36186. this._currentEffect.setTexture(name, texture);
  36187. };
  36188. /**
  36189. * Directly updates the value of the uniform in the cache AND on the GPU.
  36190. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36191. * @param {number[]|Float32Array} data Flattened data
  36192. */
  36193. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36194. this.updateUniform(uniformName, data, data.length);
  36195. this.update();
  36196. };
  36197. /**
  36198. * Binds this uniform buffer to an effect.
  36199. * @param {Effect} effect
  36200. * @param {string} name Name of the uniform block in the shader.
  36201. */
  36202. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36203. this._currentEffect = effect;
  36204. if (this._noUBO || !this._buffer) {
  36205. return;
  36206. }
  36207. effect.bindUniformBuffer(this._buffer, name);
  36208. };
  36209. /**
  36210. * Disposes the uniform buffer.
  36211. */
  36212. UniformBuffer.prototype.dispose = function () {
  36213. if (this._noUBO) {
  36214. return;
  36215. }
  36216. var index = this._engine._uniformBuffers.indexOf(this);
  36217. if (index !== -1) {
  36218. this._engine._uniformBuffers.splice(index, 1);
  36219. }
  36220. if (!this._buffer) {
  36221. return;
  36222. }
  36223. if (this._engine._releaseBuffer(this._buffer)) {
  36224. this._buffer = null;
  36225. }
  36226. };
  36227. // Pool for avoiding memory leaks
  36228. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36229. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36230. return UniformBuffer;
  36231. }());
  36232. BABYLON.UniformBuffer = UniformBuffer;
  36233. })(BABYLON || (BABYLON = {}));
  36234. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36235. var BABYLON;
  36236. (function (BABYLON) {
  36237. /**
  36238. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36239. */
  36240. var VertexData = /** @class */ (function () {
  36241. function VertexData() {
  36242. }
  36243. /**
  36244. * Uses the passed data array to set the set the values for the specified kind of data
  36245. * @param data a linear array of floating numbers
  36246. * @param kind the type of data that is being set, eg positions, colors etc
  36247. */
  36248. VertexData.prototype.set = function (data, kind) {
  36249. switch (kind) {
  36250. case BABYLON.VertexBuffer.PositionKind:
  36251. this.positions = data;
  36252. break;
  36253. case BABYLON.VertexBuffer.NormalKind:
  36254. this.normals = data;
  36255. break;
  36256. case BABYLON.VertexBuffer.TangentKind:
  36257. this.tangents = data;
  36258. break;
  36259. case BABYLON.VertexBuffer.UVKind:
  36260. this.uvs = data;
  36261. break;
  36262. case BABYLON.VertexBuffer.UV2Kind:
  36263. this.uvs2 = data;
  36264. break;
  36265. case BABYLON.VertexBuffer.UV3Kind:
  36266. this.uvs3 = data;
  36267. break;
  36268. case BABYLON.VertexBuffer.UV4Kind:
  36269. this.uvs4 = data;
  36270. break;
  36271. case BABYLON.VertexBuffer.UV5Kind:
  36272. this.uvs5 = data;
  36273. break;
  36274. case BABYLON.VertexBuffer.UV6Kind:
  36275. this.uvs6 = data;
  36276. break;
  36277. case BABYLON.VertexBuffer.ColorKind:
  36278. this.colors = data;
  36279. break;
  36280. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36281. this.matricesIndices = data;
  36282. break;
  36283. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36284. this.matricesWeights = data;
  36285. break;
  36286. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36287. this.matricesIndicesExtra = data;
  36288. break;
  36289. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36290. this.matricesWeightsExtra = data;
  36291. break;
  36292. }
  36293. };
  36294. /**
  36295. * Associates the vertexData to the passed Mesh.
  36296. * Sets it as updatable or not (default `false`)
  36297. * @param mesh the mesh the vertexData is applied to
  36298. * @param updatable when used and having the value true allows new data to update the vertexData
  36299. * @returns the VertexData
  36300. */
  36301. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36302. this._applyTo(mesh, updatable);
  36303. return this;
  36304. };
  36305. /**
  36306. * Associates the vertexData to the passed Geometry.
  36307. * Sets it as updatable or not (default `false`)
  36308. * @param geometry the geometry the vertexData is applied to
  36309. * @param updatable when used and having the value true allows new data to update the vertexData
  36310. * @returns VertexData
  36311. */
  36312. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36313. this._applyTo(geometry, updatable);
  36314. return this;
  36315. };
  36316. /**
  36317. * Updates the associated mesh
  36318. * @param mesh the mesh to be updated
  36319. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36320. * @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
  36321. * @returns VertexData
  36322. */
  36323. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36324. this._update(mesh);
  36325. return this;
  36326. };
  36327. /**
  36328. * Updates the associated geometry
  36329. * @param geometry the geometry to be updated
  36330. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36331. * @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
  36332. * @returns VertexData.
  36333. */
  36334. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36335. this._update(geometry);
  36336. return this;
  36337. };
  36338. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36339. if (updatable === void 0) { updatable = false; }
  36340. if (this.positions) {
  36341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36342. }
  36343. if (this.normals) {
  36344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36345. }
  36346. if (this.tangents) {
  36347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36348. }
  36349. if (this.uvs) {
  36350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36351. }
  36352. if (this.uvs2) {
  36353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36354. }
  36355. if (this.uvs3) {
  36356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36357. }
  36358. if (this.uvs4) {
  36359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36360. }
  36361. if (this.uvs5) {
  36362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36363. }
  36364. if (this.uvs6) {
  36365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36366. }
  36367. if (this.colors) {
  36368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36369. }
  36370. if (this.matricesIndices) {
  36371. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36372. }
  36373. if (this.matricesWeights) {
  36374. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36375. }
  36376. if (this.matricesIndicesExtra) {
  36377. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36378. }
  36379. if (this.matricesWeightsExtra) {
  36380. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36381. }
  36382. if (this.indices) {
  36383. meshOrGeometry.setIndices(this.indices, null, updatable);
  36384. }
  36385. else {
  36386. meshOrGeometry.setIndices([], null);
  36387. }
  36388. return this;
  36389. };
  36390. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36391. if (this.positions) {
  36392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36393. }
  36394. if (this.normals) {
  36395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36396. }
  36397. if (this.tangents) {
  36398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36399. }
  36400. if (this.uvs) {
  36401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36402. }
  36403. if (this.uvs2) {
  36404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36405. }
  36406. if (this.uvs3) {
  36407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36408. }
  36409. if (this.uvs4) {
  36410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36411. }
  36412. if (this.uvs5) {
  36413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36414. }
  36415. if (this.uvs6) {
  36416. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36417. }
  36418. if (this.colors) {
  36419. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36420. }
  36421. if (this.matricesIndices) {
  36422. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36423. }
  36424. if (this.matricesWeights) {
  36425. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36426. }
  36427. if (this.matricesIndicesExtra) {
  36428. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36429. }
  36430. if (this.matricesWeightsExtra) {
  36431. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36432. }
  36433. if (this.indices) {
  36434. meshOrGeometry.setIndices(this.indices, null);
  36435. }
  36436. return this;
  36437. };
  36438. /**
  36439. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36440. * @param matrix the transforming matrix
  36441. * @returns the VertexData
  36442. */
  36443. VertexData.prototype.transform = function (matrix) {
  36444. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36445. var transformed = BABYLON.Vector3.Zero();
  36446. var index;
  36447. if (this.positions) {
  36448. var position = BABYLON.Vector3.Zero();
  36449. for (index = 0; index < this.positions.length; index += 3) {
  36450. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36451. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36452. this.positions[index] = transformed.x;
  36453. this.positions[index + 1] = transformed.y;
  36454. this.positions[index + 2] = transformed.z;
  36455. }
  36456. }
  36457. if (this.normals) {
  36458. var normal = BABYLON.Vector3.Zero();
  36459. for (index = 0; index < this.normals.length; index += 3) {
  36460. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36461. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36462. this.normals[index] = transformed.x;
  36463. this.normals[index + 1] = transformed.y;
  36464. this.normals[index + 2] = transformed.z;
  36465. }
  36466. }
  36467. if (this.tangents) {
  36468. var tangent = BABYLON.Vector4.Zero();
  36469. var tangentTransformed = BABYLON.Vector4.Zero();
  36470. for (index = 0; index < this.tangents.length; index += 4) {
  36471. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36472. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36473. this.tangents[index] = tangentTransformed.x;
  36474. this.tangents[index + 1] = tangentTransformed.y;
  36475. this.tangents[index + 2] = tangentTransformed.z;
  36476. this.tangents[index + 3] = tangentTransformed.w;
  36477. }
  36478. }
  36479. if (flip && this.indices) {
  36480. for (index = 0; index < this.indices.length; index += 3) {
  36481. var tmp = this.indices[index + 1];
  36482. this.indices[index + 1] = this.indices[index + 2];
  36483. this.indices[index + 2] = tmp;
  36484. }
  36485. }
  36486. return this;
  36487. };
  36488. /**
  36489. * Merges the passed VertexData into the current one
  36490. * @param other the VertexData to be merged into the current one
  36491. * @returns the modified VertexData
  36492. */
  36493. VertexData.prototype.merge = function (other) {
  36494. this._validate();
  36495. other._validate();
  36496. if (!this.normals !== !other.normals ||
  36497. !this.tangents !== !other.tangents ||
  36498. !this.uvs !== !other.uvs ||
  36499. !this.uvs2 !== !other.uvs2 ||
  36500. !this.uvs3 !== !other.uvs3 ||
  36501. !this.uvs4 !== !other.uvs4 ||
  36502. !this.uvs5 !== !other.uvs5 ||
  36503. !this.uvs6 !== !other.uvs6 ||
  36504. !this.colors !== !other.colors ||
  36505. !this.matricesIndices !== !other.matricesIndices ||
  36506. !this.matricesWeights !== !other.matricesWeights ||
  36507. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36508. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36509. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36510. }
  36511. if (other.indices) {
  36512. if (!this.indices) {
  36513. this.indices = [];
  36514. }
  36515. var offset = this.positions ? this.positions.length / 3 : 0;
  36516. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36517. if (isSrcTypedArray) {
  36518. var len = this.indices.length + other.indices.length;
  36519. var temp = this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36520. temp.set(this.indices);
  36521. var decal = this.indices.length;
  36522. for (var index = 0; index < other.indices.length; index++) {
  36523. temp[decal + index] = other.indices[index] + offset;
  36524. }
  36525. this.indices = temp;
  36526. }
  36527. else {
  36528. for (var index = 0; index < other.indices.length; index++) {
  36529. this.indices.push(other.indices[index] + offset);
  36530. }
  36531. }
  36532. }
  36533. this.positions = this._mergeElement(this.positions, other.positions);
  36534. this.normals = this._mergeElement(this.normals, other.normals);
  36535. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36536. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36537. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36538. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36539. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36540. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36541. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36542. this.colors = this._mergeElement(this.colors, other.colors);
  36543. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36544. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36545. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36546. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36547. return this;
  36548. };
  36549. VertexData.prototype._mergeElement = function (source, other) {
  36550. if (!source) {
  36551. return other;
  36552. }
  36553. if (!other) {
  36554. return source;
  36555. }
  36556. var len = other.length + source.length;
  36557. var isSrcTypedArray = source instanceof Float32Array;
  36558. var isOthTypedArray = other instanceof Float32Array;
  36559. // use non-loop method when the source is Float32Array
  36560. if (isSrcTypedArray) {
  36561. var ret32 = new Float32Array(len);
  36562. ret32.set(source);
  36563. ret32.set(other, source.length);
  36564. return ret32;
  36565. // source is number[], when other is also use concat
  36566. }
  36567. else if (!isOthTypedArray) {
  36568. return source.concat(other);
  36569. // source is a number[], but other is a Float32Array, loop required
  36570. }
  36571. else {
  36572. var ret = source.slice(0); // copy source to a separate array
  36573. for (var i = 0, len = other.length; i < len; i++) {
  36574. ret.push(other[i]);
  36575. }
  36576. return ret;
  36577. }
  36578. };
  36579. VertexData.prototype._validate = function () {
  36580. if (!this.positions) {
  36581. throw new Error("Positions are required");
  36582. }
  36583. var getElementCount = function (kind, values) {
  36584. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36585. if ((values.length % stride) !== 0) {
  36586. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36587. }
  36588. return values.length / stride;
  36589. };
  36590. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36591. var validateElementCount = function (kind, values) {
  36592. var elementCount = getElementCount(kind, values);
  36593. if (elementCount !== positionsElementCount) {
  36594. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36595. }
  36596. };
  36597. if (this.normals)
  36598. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36599. if (this.tangents)
  36600. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36601. if (this.uvs)
  36602. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36603. if (this.uvs2)
  36604. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36605. if (this.uvs3)
  36606. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36607. if (this.uvs4)
  36608. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36609. if (this.uvs5)
  36610. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36611. if (this.uvs6)
  36612. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36613. if (this.colors)
  36614. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36615. if (this.matricesIndices)
  36616. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36617. if (this.matricesWeights)
  36618. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36619. if (this.matricesIndicesExtra)
  36620. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36621. if (this.matricesWeightsExtra)
  36622. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36623. };
  36624. /**
  36625. * Serializes the VertexData
  36626. * @returns a serialized object
  36627. */
  36628. VertexData.prototype.serialize = function () {
  36629. var serializationObject = this.serialize();
  36630. if (this.positions) {
  36631. serializationObject.positions = this.positions;
  36632. }
  36633. if (this.normals) {
  36634. serializationObject.normals = this.normals;
  36635. }
  36636. if (this.tangents) {
  36637. serializationObject.tangents = this.tangents;
  36638. }
  36639. if (this.uvs) {
  36640. serializationObject.uvs = this.uvs;
  36641. }
  36642. if (this.uvs2) {
  36643. serializationObject.uvs2 = this.uvs2;
  36644. }
  36645. if (this.uvs3) {
  36646. serializationObject.uvs3 = this.uvs3;
  36647. }
  36648. if (this.uvs4) {
  36649. serializationObject.uvs4 = this.uvs4;
  36650. }
  36651. if (this.uvs5) {
  36652. serializationObject.uvs5 = this.uvs5;
  36653. }
  36654. if (this.uvs6) {
  36655. serializationObject.uvs6 = this.uvs6;
  36656. }
  36657. if (this.colors) {
  36658. serializationObject.colors = this.colors;
  36659. }
  36660. if (this.matricesIndices) {
  36661. serializationObject.matricesIndices = this.matricesIndices;
  36662. serializationObject.matricesIndices._isExpanded = true;
  36663. }
  36664. if (this.matricesWeights) {
  36665. serializationObject.matricesWeights = this.matricesWeights;
  36666. }
  36667. if (this.matricesIndicesExtra) {
  36668. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36669. serializationObject.matricesIndicesExtra._isExpanded = true;
  36670. }
  36671. if (this.matricesWeightsExtra) {
  36672. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36673. }
  36674. serializationObject.indices = this.indices;
  36675. return serializationObject;
  36676. };
  36677. // Statics
  36678. /**
  36679. * Extracts the vertexData from a mesh
  36680. * @param mesh the mesh from which to extract the VertexData
  36681. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36682. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36683. * @returns the object VertexData associated to the passed mesh
  36684. */
  36685. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36686. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36687. };
  36688. /**
  36689. * Extracts the vertexData from the geometry
  36690. * @param geometry the geometry from which to extract the VertexData
  36691. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36692. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36693. * @returns the object VertexData associated to the passed mesh
  36694. */
  36695. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36696. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36697. };
  36698. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36699. var result = new VertexData();
  36700. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36701. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36702. }
  36703. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36704. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36705. }
  36706. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36707. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36708. }
  36709. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36710. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36711. }
  36712. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36713. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36714. }
  36715. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36716. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36717. }
  36718. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36719. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36720. }
  36721. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36722. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36723. }
  36724. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36725. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36726. }
  36727. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36728. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36729. }
  36730. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36731. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36732. }
  36733. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36734. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36735. }
  36736. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36737. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36738. }
  36739. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36740. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36741. }
  36742. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36743. return result;
  36744. };
  36745. /**
  36746. * Creates the VertexData for a Ribbon
  36747. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36748. * * pathArray array of paths, each of which an array of successive Vector3
  36749. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36750. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36751. * * 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
  36752. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36753. * * 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)
  36754. * * 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)
  36755. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36756. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36757. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36758. * @returns the VertexData of the ribbon
  36759. */
  36760. VertexData.CreateRibbon = function (options) {
  36761. var pathArray = options.pathArray;
  36762. var closeArray = options.closeArray || false;
  36763. var closePath = options.closePath || false;
  36764. var invertUV = options.invertUV || false;
  36765. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36766. var offset = options.offset || defaultOffset;
  36767. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36768. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36769. var customUV = options.uvs;
  36770. var customColors = options.colors;
  36771. var positions = [];
  36772. var indices = [];
  36773. var normals = [];
  36774. var uvs = [];
  36775. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36776. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36777. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36778. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36779. var minlg; // minimal length among all paths from pathArray
  36780. var lg = []; // array of path lengths : nb of vertex per path
  36781. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36782. var p; // path iterator
  36783. var i; // point iterator
  36784. var j; // point iterator
  36785. // if single path in pathArray
  36786. if (pathArray.length < 2) {
  36787. var ar1 = [];
  36788. var ar2 = [];
  36789. for (i = 0; i < pathArray[0].length - offset; i++) {
  36790. ar1.push(pathArray[0][i]);
  36791. ar2.push(pathArray[0][i + offset]);
  36792. }
  36793. pathArray = [ar1, ar2];
  36794. }
  36795. // positions and horizontal distances (u)
  36796. var idc = 0;
  36797. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36798. var path;
  36799. var l;
  36800. minlg = pathArray[0].length;
  36801. var vectlg;
  36802. var dist;
  36803. for (p = 0; p < pathArray.length; p++) {
  36804. uTotalDistance[p] = 0;
  36805. us[p] = [0];
  36806. path = pathArray[p];
  36807. l = path.length;
  36808. minlg = (minlg < l) ? minlg : l;
  36809. j = 0;
  36810. while (j < l) {
  36811. positions.push(path[j].x, path[j].y, path[j].z);
  36812. if (j > 0) {
  36813. vectlg = path[j].subtract(path[j - 1]).length();
  36814. dist = vectlg + uTotalDistance[p];
  36815. us[p].push(dist);
  36816. uTotalDistance[p] = dist;
  36817. }
  36818. j++;
  36819. }
  36820. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36821. j--;
  36822. positions.push(path[0].x, path[0].y, path[0].z);
  36823. vectlg = path[j].subtract(path[0]).length();
  36824. dist = vectlg + uTotalDistance[p];
  36825. us[p].push(dist);
  36826. uTotalDistance[p] = dist;
  36827. }
  36828. lg[p] = l + closePathCorr;
  36829. idx[p] = idc;
  36830. idc += (l + closePathCorr);
  36831. }
  36832. // vertical distances (v)
  36833. var path1;
  36834. var path2;
  36835. var vertex1 = null;
  36836. var vertex2 = null;
  36837. for (i = 0; i < minlg + closePathCorr; i++) {
  36838. vTotalDistance[i] = 0;
  36839. vs[i] = [0];
  36840. for (p = 0; p < pathArray.length - 1; p++) {
  36841. path1 = pathArray[p];
  36842. path2 = pathArray[p + 1];
  36843. if (i === minlg) { // closePath
  36844. vertex1 = path1[0];
  36845. vertex2 = path2[0];
  36846. }
  36847. else {
  36848. vertex1 = path1[i];
  36849. vertex2 = path2[i];
  36850. }
  36851. vectlg = vertex2.subtract(vertex1).length();
  36852. dist = vectlg + vTotalDistance[i];
  36853. vs[i].push(dist);
  36854. vTotalDistance[i] = dist;
  36855. }
  36856. if (closeArray && vertex2 && vertex1) {
  36857. path1 = pathArray[p];
  36858. path2 = pathArray[0];
  36859. if (i === minlg) { // closePath
  36860. vertex2 = path2[0];
  36861. }
  36862. vectlg = vertex2.subtract(vertex1).length();
  36863. dist = vectlg + vTotalDistance[i];
  36864. vTotalDistance[i] = dist;
  36865. }
  36866. }
  36867. // uvs
  36868. var u;
  36869. var v;
  36870. if (customUV) {
  36871. for (p = 0; p < customUV.length; p++) {
  36872. uvs.push(customUV[p].x, customUV[p].y);
  36873. }
  36874. }
  36875. else {
  36876. for (p = 0; p < pathArray.length; p++) {
  36877. for (i = 0; i < minlg + closePathCorr; i++) {
  36878. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36879. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36880. if (invertUV) {
  36881. uvs.push(v, u);
  36882. }
  36883. else {
  36884. uvs.push(u, v);
  36885. }
  36886. }
  36887. }
  36888. }
  36889. // indices
  36890. p = 0; // path index
  36891. var pi = 0; // positions array index
  36892. var l1 = lg[p] - 1; // path1 length
  36893. var l2 = lg[p + 1] - 1; // path2 length
  36894. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36895. var shft = idx[1] - idx[0]; // shift
  36896. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36897. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36898. // 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
  36899. indices.push(pi, pi + shft, pi + 1);
  36900. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36901. pi += 1;
  36902. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36903. p++;
  36904. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36905. shft = idx[0] - idx[p];
  36906. l1 = lg[p] - 1;
  36907. l2 = lg[0] - 1;
  36908. }
  36909. else {
  36910. shft = idx[p + 1] - idx[p];
  36911. l1 = lg[p] - 1;
  36912. l2 = lg[p + 1] - 1;
  36913. }
  36914. pi = idx[p];
  36915. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36916. }
  36917. }
  36918. // normals
  36919. VertexData.ComputeNormals(positions, indices, normals);
  36920. if (closePath) { // update both the first and last vertex normals to their average value
  36921. var indexFirst = 0;
  36922. var indexLast = 0;
  36923. for (p = 0; p < pathArray.length; p++) {
  36924. indexFirst = idx[p] * 3;
  36925. if (p + 1 < pathArray.length) {
  36926. indexLast = (idx[p + 1] - 1) * 3;
  36927. }
  36928. else {
  36929. indexLast = normals.length - 3;
  36930. }
  36931. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36932. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36933. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36934. normals[indexLast] = normals[indexFirst];
  36935. normals[indexLast + 1] = normals[indexFirst + 1];
  36936. normals[indexLast + 2] = normals[indexFirst + 2];
  36937. }
  36938. }
  36939. // sides
  36940. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36941. // Colors
  36942. var colors = null;
  36943. if (customColors) {
  36944. colors = new Float32Array(customColors.length * 4);
  36945. for (var c = 0; c < customColors.length; c++) {
  36946. colors[c * 4] = customColors[c].r;
  36947. colors[c * 4 + 1] = customColors[c].g;
  36948. colors[c * 4 + 2] = customColors[c].b;
  36949. colors[c * 4 + 3] = customColors[c].a;
  36950. }
  36951. }
  36952. // Result
  36953. var vertexData = new VertexData();
  36954. var positions32 = new Float32Array(positions);
  36955. var normals32 = new Float32Array(normals);
  36956. var uvs32 = new Float32Array(uvs);
  36957. vertexData.indices = indices;
  36958. vertexData.positions = positions32;
  36959. vertexData.normals = normals32;
  36960. vertexData.uvs = uvs32;
  36961. if (colors) {
  36962. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36963. }
  36964. if (closePath) {
  36965. vertexData._idx = idx;
  36966. }
  36967. return vertexData;
  36968. };
  36969. /**
  36970. * Creates the VertexData for a box
  36971. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36972. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36973. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36974. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36975. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36976. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36977. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36978. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36979. * * 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)
  36980. * * 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)
  36981. * @returns the VertexData of the box
  36982. */
  36983. VertexData.CreateBox = function (options) {
  36984. var normalsSource = [
  36985. new BABYLON.Vector3(0, 0, 1),
  36986. new BABYLON.Vector3(0, 0, -1),
  36987. new BABYLON.Vector3(1, 0, 0),
  36988. new BABYLON.Vector3(-1, 0, 0),
  36989. new BABYLON.Vector3(0, 1, 0),
  36990. new BABYLON.Vector3(0, -1, 0)
  36991. ];
  36992. var indices = [];
  36993. var positions = [];
  36994. var normals = [];
  36995. var uvs = [];
  36996. var width = options.width || options.size || 1;
  36997. var height = options.height || options.size || 1;
  36998. var depth = options.depth || options.size || 1;
  36999. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37000. var faceUV = options.faceUV || new Array(6);
  37001. var faceColors = options.faceColors;
  37002. var colors = [];
  37003. // default face colors and UV if undefined
  37004. for (var f = 0; f < 6; f++) {
  37005. if (faceUV[f] === undefined) {
  37006. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37007. }
  37008. if (faceColors && faceColors[f] === undefined) {
  37009. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37010. }
  37011. }
  37012. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37013. // Create each face in turn.
  37014. for (var index = 0; index < normalsSource.length; index++) {
  37015. var normal = normalsSource[index];
  37016. // Get two vectors perpendicular to the face normal and to each other.
  37017. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37018. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37019. // Six indices (two triangles) per face.
  37020. var verticesLength = positions.length / 3;
  37021. indices.push(verticesLength);
  37022. indices.push(verticesLength + 1);
  37023. indices.push(verticesLength + 2);
  37024. indices.push(verticesLength);
  37025. indices.push(verticesLength + 2);
  37026. indices.push(verticesLength + 3);
  37027. // Four vertices per face.
  37028. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37029. positions.push(vertex.x, vertex.y, vertex.z);
  37030. normals.push(normal.x, normal.y, normal.z);
  37031. uvs.push(faceUV[index].z, faceUV[index].w);
  37032. if (faceColors) {
  37033. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37034. }
  37035. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37036. positions.push(vertex.x, vertex.y, vertex.z);
  37037. normals.push(normal.x, normal.y, normal.z);
  37038. uvs.push(faceUV[index].x, faceUV[index].w);
  37039. if (faceColors) {
  37040. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37041. }
  37042. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37043. positions.push(vertex.x, vertex.y, vertex.z);
  37044. normals.push(normal.x, normal.y, normal.z);
  37045. uvs.push(faceUV[index].x, faceUV[index].y);
  37046. if (faceColors) {
  37047. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37048. }
  37049. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37050. positions.push(vertex.x, vertex.y, vertex.z);
  37051. normals.push(normal.x, normal.y, normal.z);
  37052. uvs.push(faceUV[index].z, faceUV[index].y);
  37053. if (faceColors) {
  37054. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37055. }
  37056. }
  37057. // sides
  37058. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37059. // Result
  37060. var vertexData = new VertexData();
  37061. vertexData.indices = indices;
  37062. vertexData.positions = positions;
  37063. vertexData.normals = normals;
  37064. vertexData.uvs = uvs;
  37065. if (faceColors) {
  37066. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37067. vertexData.colors = totalColors;
  37068. }
  37069. return vertexData;
  37070. };
  37071. /**
  37072. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37073. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37074. * * segments sets the number of horizontal strips optional, default 32
  37075. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37076. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37077. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37078. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37079. * * 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
  37080. * * 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
  37081. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37082. * * 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)
  37083. * * 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)
  37084. * @returns the VertexData of the ellipsoid
  37085. */
  37086. VertexData.CreateSphere = function (options) {
  37087. var segments = options.segments || 32;
  37088. var diameterX = options.diameterX || options.diameter || 1;
  37089. var diameterY = options.diameterY || options.diameter || 1;
  37090. var diameterZ = options.diameterZ || options.diameter || 1;
  37091. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37092. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37093. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37094. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37095. var totalZRotationSteps = 2 + segments;
  37096. var totalYRotationSteps = 2 * totalZRotationSteps;
  37097. var indices = [];
  37098. var positions = [];
  37099. var normals = [];
  37100. var uvs = [];
  37101. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37102. var normalizedZ = zRotationStep / totalZRotationSteps;
  37103. var angleZ = normalizedZ * Math.PI * slice;
  37104. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37105. var normalizedY = yRotationStep / totalYRotationSteps;
  37106. var angleY = normalizedY * Math.PI * 2 * arc;
  37107. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37108. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37109. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37110. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37111. var vertex = complete.multiply(radius);
  37112. var normal = complete.divide(radius).normalize();
  37113. positions.push(vertex.x, vertex.y, vertex.z);
  37114. normals.push(normal.x, normal.y, normal.z);
  37115. uvs.push(normalizedY, normalizedZ);
  37116. }
  37117. if (zRotationStep > 0) {
  37118. var verticesCount = positions.length / 3;
  37119. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37120. indices.push((firstIndex));
  37121. indices.push((firstIndex + 1));
  37122. indices.push(firstIndex + totalYRotationSteps + 1);
  37123. indices.push((firstIndex + totalYRotationSteps + 1));
  37124. indices.push((firstIndex + 1));
  37125. indices.push((firstIndex + totalYRotationSteps + 2));
  37126. }
  37127. }
  37128. }
  37129. // Sides
  37130. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37131. // Result
  37132. var vertexData = new VertexData();
  37133. vertexData.indices = indices;
  37134. vertexData.positions = positions;
  37135. vertexData.normals = normals;
  37136. vertexData.uvs = uvs;
  37137. return vertexData;
  37138. };
  37139. /**
  37140. * Creates the VertexData for a cylinder, cone or prism
  37141. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37142. * * height sets the height (y direction) of the cylinder, optional, default 2
  37143. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37144. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37145. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37146. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37147. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37148. * * 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
  37149. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37150. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37151. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37152. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37153. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37154. * * 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)
  37155. * * 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)
  37156. * @returns the VertexData of the cylinder, cone or prism
  37157. */
  37158. VertexData.CreateCylinder = function (options) {
  37159. var height = options.height || 2;
  37160. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37161. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37162. var tessellation = options.tessellation || 24;
  37163. var subdivisions = options.subdivisions || 1;
  37164. var hasRings = options.hasRings ? true : false;
  37165. var enclose = options.enclose ? true : false;
  37166. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37167. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37168. var faceUV = options.faceUV || new Array(3);
  37169. var faceColors = options.faceColors;
  37170. // default face colors and UV if undefined
  37171. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37172. var ringNb = (hasRings) ? subdivisions : 1;
  37173. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37174. var f;
  37175. for (f = 0; f < surfaceNb; f++) {
  37176. if (faceColors && faceColors[f] === undefined) {
  37177. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37178. }
  37179. }
  37180. for (f = 0; f < surfaceNb; f++) {
  37181. if (faceUV && faceUV[f] === undefined) {
  37182. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37183. }
  37184. }
  37185. var indices = new Array();
  37186. var positions = new Array();
  37187. var normals = new Array();
  37188. var uvs = new Array();
  37189. var colors = new Array();
  37190. var angle_step = Math.PI * 2 * arc / tessellation;
  37191. var angle;
  37192. var h;
  37193. var radius;
  37194. var tan = (diameterBottom - diameterTop) / 2 / height;
  37195. var ringVertex = BABYLON.Vector3.Zero();
  37196. var ringNormal = BABYLON.Vector3.Zero();
  37197. var ringFirstVertex = BABYLON.Vector3.Zero();
  37198. var ringFirstNormal = BABYLON.Vector3.Zero();
  37199. var quadNormal = BABYLON.Vector3.Zero();
  37200. var Y = BABYLON.Axis.Y;
  37201. // positions, normals, uvs
  37202. var i;
  37203. var j;
  37204. var r;
  37205. var ringIdx = 1;
  37206. var s = 1; // surface index
  37207. var cs = 0;
  37208. var v = 0;
  37209. for (i = 0; i <= subdivisions; i++) {
  37210. h = i / subdivisions;
  37211. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37212. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37213. for (r = 0; r < ringIdx; r++) {
  37214. if (hasRings) {
  37215. s += r;
  37216. }
  37217. if (enclose) {
  37218. s += 2 * r;
  37219. }
  37220. for (j = 0; j <= tessellation; j++) {
  37221. angle = j * angle_step;
  37222. // position
  37223. ringVertex.x = Math.cos(-angle) * radius;
  37224. ringVertex.y = -height / 2 + h * height;
  37225. ringVertex.z = Math.sin(-angle) * radius;
  37226. // normal
  37227. if (diameterTop === 0 && i === subdivisions) {
  37228. // if no top cap, reuse former normals
  37229. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37230. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37231. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37232. }
  37233. else {
  37234. ringNormal.x = ringVertex.x;
  37235. ringNormal.z = ringVertex.z;
  37236. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37237. ringNormal.normalize();
  37238. }
  37239. // keep first ring vertex values for enclose
  37240. if (j === 0) {
  37241. ringFirstVertex.copyFrom(ringVertex);
  37242. ringFirstNormal.copyFrom(ringNormal);
  37243. }
  37244. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37245. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37246. if (hasRings) {
  37247. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37248. }
  37249. else {
  37250. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37251. }
  37252. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37253. if (faceColors) {
  37254. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37255. }
  37256. }
  37257. // if enclose, add four vertices and their dedicated normals
  37258. if (arc !== 1 && enclose) {
  37259. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37260. positions.push(0, ringVertex.y, 0);
  37261. positions.push(0, ringVertex.y, 0);
  37262. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37263. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37264. quadNormal.normalize();
  37265. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37266. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37267. quadNormal.normalize();
  37268. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37269. if (hasRings) {
  37270. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37271. }
  37272. else {
  37273. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37274. }
  37275. uvs.push(faceUV[s + 1].x, v);
  37276. uvs.push(faceUV[s + 1].z, v);
  37277. if (hasRings) {
  37278. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37279. }
  37280. else {
  37281. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37282. }
  37283. uvs.push(faceUV[s + 2].x, v);
  37284. uvs.push(faceUV[s + 2].z, v);
  37285. if (faceColors) {
  37286. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37287. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37288. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37289. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37290. }
  37291. }
  37292. if (cs !== s) {
  37293. cs = s;
  37294. }
  37295. }
  37296. }
  37297. // indices
  37298. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37299. var s;
  37300. i = 0;
  37301. for (s = 0; s < subdivisions; s++) {
  37302. var i0 = 0;
  37303. var i1 = 0;
  37304. var i2 = 0;
  37305. var i3 = 0;
  37306. for (j = 0; j < tessellation; j++) {
  37307. i0 = i * (e + 1) + j;
  37308. i1 = (i + 1) * (e + 1) + j;
  37309. i2 = i * (e + 1) + (j + 1);
  37310. i3 = (i + 1) * (e + 1) + (j + 1);
  37311. indices.push(i0, i1, i2);
  37312. indices.push(i3, i2, i1);
  37313. }
  37314. if (arc !== 1 && enclose) { // if enclose, add two quads
  37315. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37316. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37317. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37318. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37319. }
  37320. i = (hasRings) ? (i + 2) : (i + 1);
  37321. }
  37322. // Caps
  37323. var createCylinderCap = function (isTop) {
  37324. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37325. if (radius === 0) {
  37326. return;
  37327. }
  37328. // Cap positions, normals & uvs
  37329. var angle;
  37330. var circleVector;
  37331. var i;
  37332. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37333. var c = null;
  37334. if (faceColors) {
  37335. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37336. }
  37337. // cap center
  37338. var vbase = positions.length / 3;
  37339. var offset = isTop ? height / 2 : -height / 2;
  37340. var center = new BABYLON.Vector3(0, offset, 0);
  37341. positions.push(center.x, center.y, center.z);
  37342. normals.push(0, isTop ? 1 : -1, 0);
  37343. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37344. if (c) {
  37345. colors.push(c.r, c.g, c.b, c.a);
  37346. }
  37347. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37348. for (i = 0; i <= tessellation; i++) {
  37349. angle = Math.PI * 2 * i * arc / tessellation;
  37350. var cos = Math.cos(-angle);
  37351. var sin = Math.sin(-angle);
  37352. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37353. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37354. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37355. normals.push(0, isTop ? 1 : -1, 0);
  37356. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37357. if (c) {
  37358. colors.push(c.r, c.g, c.b, c.a);
  37359. }
  37360. }
  37361. // Cap indices
  37362. for (i = 0; i < tessellation; i++) {
  37363. if (!isTop) {
  37364. indices.push(vbase);
  37365. indices.push(vbase + (i + 1));
  37366. indices.push(vbase + (i + 2));
  37367. }
  37368. else {
  37369. indices.push(vbase);
  37370. indices.push(vbase + (i + 2));
  37371. indices.push(vbase + (i + 1));
  37372. }
  37373. }
  37374. };
  37375. // add caps to geometry
  37376. createCylinderCap(false);
  37377. createCylinderCap(true);
  37378. // Sides
  37379. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37380. var vertexData = new VertexData();
  37381. vertexData.indices = indices;
  37382. vertexData.positions = positions;
  37383. vertexData.normals = normals;
  37384. vertexData.uvs = uvs;
  37385. if (faceColors) {
  37386. vertexData.colors = colors;
  37387. }
  37388. return vertexData;
  37389. };
  37390. /**
  37391. * Creates the VertexData for a torus
  37392. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37393. * * diameter the diameter of the torus, optional default 1
  37394. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37395. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37396. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37397. * * 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)
  37398. * * 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)
  37399. * @returns the VertexData of the torus
  37400. */
  37401. VertexData.CreateTorus = function (options) {
  37402. var indices = [];
  37403. var positions = [];
  37404. var normals = [];
  37405. var uvs = [];
  37406. var diameter = options.diameter || 1;
  37407. var thickness = options.thickness || 0.5;
  37408. var tessellation = options.tessellation || 16;
  37409. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37410. var stride = tessellation + 1;
  37411. for (var i = 0; i <= tessellation; i++) {
  37412. var u = i / tessellation;
  37413. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37414. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37415. for (var j = 0; j <= tessellation; j++) {
  37416. var v = 1 - j / tessellation;
  37417. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37418. var dx = Math.cos(innerAngle);
  37419. var dy = Math.sin(innerAngle);
  37420. // Create a vertex.
  37421. var normal = new BABYLON.Vector3(dx, dy, 0);
  37422. var position = normal.scale(thickness / 2);
  37423. var textureCoordinate = new BABYLON.Vector2(u, v);
  37424. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37425. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37426. positions.push(position.x, position.y, position.z);
  37427. normals.push(normal.x, normal.y, normal.z);
  37428. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37429. // And create indices for two triangles.
  37430. var nextI = (i + 1) % stride;
  37431. var nextJ = (j + 1) % stride;
  37432. indices.push(i * stride + j);
  37433. indices.push(i * stride + nextJ);
  37434. indices.push(nextI * stride + j);
  37435. indices.push(i * stride + nextJ);
  37436. indices.push(nextI * stride + nextJ);
  37437. indices.push(nextI * stride + j);
  37438. }
  37439. }
  37440. // Sides
  37441. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37442. // Result
  37443. var vertexData = new VertexData();
  37444. vertexData.indices = indices;
  37445. vertexData.positions = positions;
  37446. vertexData.normals = normals;
  37447. vertexData.uvs = uvs;
  37448. return vertexData;
  37449. };
  37450. /**
  37451. * Creates the VertexData of the LineSystem
  37452. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37453. * - lines an array of lines, each line being an array of successive Vector3
  37454. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37455. * @returns the VertexData of the LineSystem
  37456. */
  37457. VertexData.CreateLineSystem = function (options) {
  37458. var indices = [];
  37459. var positions = [];
  37460. var lines = options.lines;
  37461. var colors = options.colors;
  37462. var vertexColors = [];
  37463. var idx = 0;
  37464. for (var l = 0; l < lines.length; l++) {
  37465. var points = lines[l];
  37466. for (var index = 0; index < points.length; index++) {
  37467. positions.push(points[index].x, points[index].y, points[index].z);
  37468. if (colors) {
  37469. var color = colors[l];
  37470. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37471. }
  37472. if (index > 0) {
  37473. indices.push(idx - 1);
  37474. indices.push(idx);
  37475. }
  37476. idx++;
  37477. }
  37478. }
  37479. var vertexData = new VertexData();
  37480. vertexData.indices = indices;
  37481. vertexData.positions = positions;
  37482. if (colors) {
  37483. vertexData.colors = vertexColors;
  37484. }
  37485. return vertexData;
  37486. };
  37487. /**
  37488. * Create the VertexData for a DashedLines
  37489. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37490. * - points an array successive Vector3
  37491. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37492. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37493. * - dashNb the intended total number of dashes, optional, default 200
  37494. * @returns the VertexData for the DashedLines
  37495. */
  37496. VertexData.CreateDashedLines = function (options) {
  37497. var dashSize = options.dashSize || 3;
  37498. var gapSize = options.gapSize || 1;
  37499. var dashNb = options.dashNb || 200;
  37500. var points = options.points;
  37501. var positions = new Array();
  37502. var indices = new Array();
  37503. var curvect = BABYLON.Vector3.Zero();
  37504. var lg = 0;
  37505. var nb = 0;
  37506. var shft = 0;
  37507. var dashshft = 0;
  37508. var curshft = 0;
  37509. var idx = 0;
  37510. var i = 0;
  37511. for (i = 0; i < points.length - 1; i++) {
  37512. points[i + 1].subtractToRef(points[i], curvect);
  37513. lg += curvect.length();
  37514. }
  37515. shft = lg / dashNb;
  37516. dashshft = dashSize * shft / (dashSize + gapSize);
  37517. for (i = 0; i < points.length - 1; i++) {
  37518. points[i + 1].subtractToRef(points[i], curvect);
  37519. nb = Math.floor(curvect.length() / shft);
  37520. curvect.normalize();
  37521. for (var j = 0; j < nb; j++) {
  37522. curshft = shft * j;
  37523. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37524. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37525. indices.push(idx, idx + 1);
  37526. idx += 2;
  37527. }
  37528. }
  37529. // Result
  37530. var vertexData = new VertexData();
  37531. vertexData.positions = positions;
  37532. vertexData.indices = indices;
  37533. return vertexData;
  37534. };
  37535. /**
  37536. * Creates the VertexData for a Ground
  37537. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37538. * - width the width (x direction) of the ground, optional, default 1
  37539. * - height the height (z direction) of the ground, optional, default 1
  37540. * - subdivisions the number of subdivisions per side, optional, default 1
  37541. * @returns the VertexData of the Ground
  37542. */
  37543. VertexData.CreateGround = function (options) {
  37544. var indices = [];
  37545. var positions = [];
  37546. var normals = [];
  37547. var uvs = [];
  37548. var row, col;
  37549. var width = options.width || 1;
  37550. var height = options.height || 1;
  37551. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37552. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37553. for (row = 0; row <= subdivisionsY; row++) {
  37554. for (col = 0; col <= subdivisionsX; col++) {
  37555. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37556. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37557. positions.push(position.x, position.y, position.z);
  37558. normals.push(normal.x, normal.y, normal.z);
  37559. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37560. }
  37561. }
  37562. for (row = 0; row < subdivisionsY; row++) {
  37563. for (col = 0; col < subdivisionsX; col++) {
  37564. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37565. indices.push(col + 1 + row * (subdivisionsX + 1));
  37566. indices.push(col + row * (subdivisionsX + 1));
  37567. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37568. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37569. indices.push(col + row * (subdivisionsX + 1));
  37570. }
  37571. }
  37572. // Result
  37573. var vertexData = new VertexData();
  37574. vertexData.indices = indices;
  37575. vertexData.positions = positions;
  37576. vertexData.normals = normals;
  37577. vertexData.uvs = uvs;
  37578. return vertexData;
  37579. };
  37580. /**
  37581. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37582. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37583. * * xmin the ground minimum X coordinate, optional, default -1
  37584. * * zmin the ground minimum Z coordinate, optional, default -1
  37585. * * xmax the ground maximum X coordinate, optional, default 1
  37586. * * zmax the ground maximum Z coordinate, optional, default 1
  37587. * * 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}
  37588. * * 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}
  37589. * @returns the VertexData of the TiledGround
  37590. */
  37591. VertexData.CreateTiledGround = function (options) {
  37592. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37593. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37594. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37595. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37596. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37597. var precision = options.precision || { w: 1, h: 1 };
  37598. var indices = new Array();
  37599. var positions = new Array();
  37600. var normals = new Array();
  37601. var uvs = new Array();
  37602. var row, col, tileRow, tileCol;
  37603. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37604. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37605. precision.w = (precision.w < 1) ? 1 : precision.w;
  37606. precision.h = (precision.h < 1) ? 1 : precision.h;
  37607. var tileSize = {
  37608. 'w': (xmax - xmin) / subdivisions.w,
  37609. 'h': (zmax - zmin) / subdivisions.h
  37610. };
  37611. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37612. // Indices
  37613. var base = positions.length / 3;
  37614. var rowLength = precision.w + 1;
  37615. for (row = 0; row < precision.h; row++) {
  37616. for (col = 0; col < precision.w; col++) {
  37617. var square = [
  37618. base + col + row * rowLength,
  37619. base + (col + 1) + row * rowLength,
  37620. base + (col + 1) + (row + 1) * rowLength,
  37621. base + col + (row + 1) * rowLength
  37622. ];
  37623. indices.push(square[1]);
  37624. indices.push(square[2]);
  37625. indices.push(square[3]);
  37626. indices.push(square[0]);
  37627. indices.push(square[1]);
  37628. indices.push(square[3]);
  37629. }
  37630. }
  37631. // Position, normals and uvs
  37632. var position = BABYLON.Vector3.Zero();
  37633. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37634. for (row = 0; row <= precision.h; row++) {
  37635. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37636. for (col = 0; col <= precision.w; col++) {
  37637. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37638. position.y = 0;
  37639. positions.push(position.x, position.y, position.z);
  37640. normals.push(normal.x, normal.y, normal.z);
  37641. uvs.push(col / precision.w, row / precision.h);
  37642. }
  37643. }
  37644. }
  37645. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37646. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37647. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37648. }
  37649. }
  37650. // Result
  37651. var vertexData = new VertexData();
  37652. vertexData.indices = indices;
  37653. vertexData.positions = positions;
  37654. vertexData.normals = normals;
  37655. vertexData.uvs = uvs;
  37656. return vertexData;
  37657. };
  37658. /**
  37659. * Creates the VertexData of the Ground designed from a heightmap
  37660. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37661. * * width the width (x direction) of the ground
  37662. * * height the height (z direction) of the ground
  37663. * * subdivisions the number of subdivisions per side
  37664. * * minHeight the minimum altitude on the ground, optional, default 0
  37665. * * maxHeight the maximum altitude on the ground, optional default 1
  37666. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37667. * * buffer the array holding the image color data
  37668. * * bufferWidth the width of image
  37669. * * bufferHeight the height of image
  37670. * @returns the VertexData of the Ground designed from a heightmap
  37671. */
  37672. VertexData.CreateGroundFromHeightMap = function (options) {
  37673. var indices = [];
  37674. var positions = [];
  37675. var normals = [];
  37676. var uvs = [];
  37677. var row, col;
  37678. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37679. // Vertices
  37680. for (row = 0; row <= options.subdivisions; row++) {
  37681. for (col = 0; col <= options.subdivisions; col++) {
  37682. 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));
  37683. // Compute height
  37684. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37685. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37686. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37687. var r = options.buffer[pos] / 255.0;
  37688. var g = options.buffer[pos + 1] / 255.0;
  37689. var b = options.buffer[pos + 2] / 255.0;
  37690. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37691. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37692. // Add vertex
  37693. positions.push(position.x, position.y, position.z);
  37694. normals.push(0, 0, 0);
  37695. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37696. }
  37697. }
  37698. // Indices
  37699. for (row = 0; row < options.subdivisions; row++) {
  37700. for (col = 0; col < options.subdivisions; col++) {
  37701. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37702. indices.push(col + 1 + row * (options.subdivisions + 1));
  37703. indices.push(col + row * (options.subdivisions + 1));
  37704. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37705. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37706. indices.push(col + row * (options.subdivisions + 1));
  37707. }
  37708. }
  37709. // Normals
  37710. VertexData.ComputeNormals(positions, indices, normals);
  37711. // Result
  37712. var vertexData = new VertexData();
  37713. vertexData.indices = indices;
  37714. vertexData.positions = positions;
  37715. vertexData.normals = normals;
  37716. vertexData.uvs = uvs;
  37717. return vertexData;
  37718. };
  37719. /**
  37720. * Creates the VertexData for a Plane
  37721. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37722. * * size sets the width and height of the plane to the value of size, optional default 1
  37723. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37724. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37725. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37726. * * 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)
  37727. * * 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)
  37728. * @returns the VertexData of the box
  37729. */
  37730. VertexData.CreatePlane = function (options) {
  37731. var indices = [];
  37732. var positions = [];
  37733. var normals = [];
  37734. var uvs = [];
  37735. var width = options.width || options.size || 1;
  37736. var height = options.height || options.size || 1;
  37737. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37738. // Vertices
  37739. var halfWidth = width / 2.0;
  37740. var halfHeight = height / 2.0;
  37741. positions.push(-halfWidth, -halfHeight, 0);
  37742. normals.push(0, 0, -1.0);
  37743. uvs.push(0.0, 0.0);
  37744. positions.push(halfWidth, -halfHeight, 0);
  37745. normals.push(0, 0, -1.0);
  37746. uvs.push(1.0, 0.0);
  37747. positions.push(halfWidth, halfHeight, 0);
  37748. normals.push(0, 0, -1.0);
  37749. uvs.push(1.0, 1.0);
  37750. positions.push(-halfWidth, halfHeight, 0);
  37751. normals.push(0, 0, -1.0);
  37752. uvs.push(0.0, 1.0);
  37753. // Indices
  37754. indices.push(0);
  37755. indices.push(1);
  37756. indices.push(2);
  37757. indices.push(0);
  37758. indices.push(2);
  37759. indices.push(3);
  37760. // Sides
  37761. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37762. // Result
  37763. var vertexData = new VertexData();
  37764. vertexData.indices = indices;
  37765. vertexData.positions = positions;
  37766. vertexData.normals = normals;
  37767. vertexData.uvs = uvs;
  37768. return vertexData;
  37769. };
  37770. /**
  37771. * Creates the VertexData of the Disc or regular Polygon
  37772. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37773. * * radius the radius of the disc, optional default 0.5
  37774. * * tessellation the number of polygon sides, optional, default 64
  37775. * * 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
  37776. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37777. * * 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)
  37778. * * 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)
  37779. * @returns the VertexData of the box
  37780. */
  37781. VertexData.CreateDisc = function (options) {
  37782. var positions = new Array();
  37783. var indices = new Array();
  37784. var normals = new Array();
  37785. var uvs = new Array();
  37786. var radius = options.radius || 0.5;
  37787. var tessellation = options.tessellation || 64;
  37788. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37789. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37790. // positions and uvs
  37791. positions.push(0, 0, 0); // disc center first
  37792. uvs.push(0.5, 0.5);
  37793. var theta = Math.PI * 2 * arc;
  37794. var step = theta / tessellation;
  37795. for (var a = 0; a < theta; a += step) {
  37796. var x = Math.cos(a);
  37797. var y = Math.sin(a);
  37798. var u = (x + 1) / 2;
  37799. var v = (1 - y) / 2;
  37800. positions.push(radius * x, radius * y, 0);
  37801. uvs.push(u, v);
  37802. }
  37803. if (arc === 1) {
  37804. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37805. uvs.push(uvs[2], uvs[3]);
  37806. }
  37807. //indices
  37808. var vertexNb = positions.length / 3;
  37809. for (var i = 1; i < vertexNb - 1; i++) {
  37810. indices.push(i + 1, 0, i);
  37811. }
  37812. // result
  37813. VertexData.ComputeNormals(positions, indices, normals);
  37814. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37815. var vertexData = new VertexData();
  37816. vertexData.indices = indices;
  37817. vertexData.positions = positions;
  37818. vertexData.normals = normals;
  37819. vertexData.uvs = uvs;
  37820. return vertexData;
  37821. };
  37822. /**
  37823. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37824. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37825. * @param polygon a mesh built from polygonTriangulation.build()
  37826. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37827. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37828. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37829. * @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)
  37830. * @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)
  37831. * @returns the VertexData of the Polygon
  37832. */
  37833. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37834. var faceUV = fUV || new Array(3);
  37835. var faceColors = fColors;
  37836. var colors = [];
  37837. // default face colors and UV if undefined
  37838. for (var f = 0; f < 3; f++) {
  37839. if (faceUV[f] === undefined) {
  37840. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37841. }
  37842. if (faceColors && faceColors[f] === undefined) {
  37843. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37844. }
  37845. }
  37846. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37847. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37848. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37849. var indices = polygon.getIndices();
  37850. // set face colours and textures
  37851. var idx = 0;
  37852. var face = 0;
  37853. for (var index = 0; index < normals.length; index += 3) {
  37854. //Edge Face no. 1
  37855. if (Math.abs(normals[index + 1]) < 0.001) {
  37856. face = 1;
  37857. }
  37858. //Top Face no. 0
  37859. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37860. face = 0;
  37861. }
  37862. //Bottom Face no. 2
  37863. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37864. face = 2;
  37865. }
  37866. idx = index / 3;
  37867. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37868. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37869. if (faceColors) {
  37870. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37871. }
  37872. }
  37873. // sides
  37874. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37875. // Result
  37876. var vertexData = new VertexData();
  37877. vertexData.indices = indices;
  37878. vertexData.positions = positions;
  37879. vertexData.normals = normals;
  37880. vertexData.uvs = uvs;
  37881. if (faceColors) {
  37882. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37883. vertexData.colors = totalColors;
  37884. }
  37885. return vertexData;
  37886. };
  37887. /**
  37888. * Creates the VertexData of the IcoSphere
  37889. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37890. * * radius the radius of the IcoSphere, optional default 1
  37891. * * radiusX allows stretching in the x direction, optional, default radius
  37892. * * radiusY allows stretching in the y direction, optional, default radius
  37893. * * radiusZ allows stretching in the z direction, optional, default radius
  37894. * * flat when true creates a flat shaded mesh, optional, default true
  37895. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37896. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37897. * * 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)
  37898. * * 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)
  37899. * @returns the VertexData of the IcoSphere
  37900. */
  37901. VertexData.CreateIcoSphere = function (options) {
  37902. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37903. var radius = options.radius || 1;
  37904. var flat = (options.flat === undefined) ? true : options.flat;
  37905. var subdivisions = options.subdivisions || 4;
  37906. var radiusX = options.radiusX || radius;
  37907. var radiusY = options.radiusY || radius;
  37908. var radiusZ = options.radiusZ || radius;
  37909. var t = (1 + Math.sqrt(5)) / 2;
  37910. // 12 vertex x,y,z
  37911. var ico_vertices = [
  37912. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37913. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37914. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37915. ];
  37916. // index of 3 vertex makes a face of icopshere
  37917. var ico_indices = [
  37918. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37919. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37920. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37921. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37922. ];
  37923. // vertex for uv have aliased position, not for UV
  37924. var vertices_unalias_id = [
  37925. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37926. // vertex alias
  37927. 0,
  37928. 2,
  37929. 3,
  37930. 3,
  37931. 3,
  37932. 4,
  37933. 7,
  37934. 8,
  37935. 9,
  37936. 9,
  37937. 10,
  37938. 11 // 23: B + 12
  37939. ];
  37940. // uv as integer step (not pixels !)
  37941. var ico_vertexuv = [
  37942. 5, 1, 3, 1, 6, 4, 0, 0,
  37943. 5, 3, 4, 2, 2, 2, 4, 0,
  37944. 2, 0, 1, 1, 6, 0, 6, 2,
  37945. // vertex alias (for same vertex on different faces)
  37946. 0, 4,
  37947. 3, 3,
  37948. 4, 4,
  37949. 3, 1,
  37950. 4, 2,
  37951. 4, 4,
  37952. 0, 2,
  37953. 1, 1,
  37954. 2, 2,
  37955. 3, 3,
  37956. 1, 3,
  37957. 2, 4 // 23: B + 12
  37958. ];
  37959. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37960. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37961. // First island of uv mapping
  37962. // v = 4h 3+ 2
  37963. // v = 3h 9+ 4
  37964. // v = 2h 9+ 5 B
  37965. // v = 1h 9 1 0
  37966. // v = 0h 3 8 7 A
  37967. // u = 0 1 2 3 4 5 6 *a
  37968. // Second island of uv mapping
  37969. // v = 4h 0+ B+ 4+
  37970. // v = 3h A+ 2+
  37971. // v = 2h 7+ 6 3+
  37972. // v = 1h 8+ 3+
  37973. // v = 0h
  37974. // u = 0 1 2 3 4 5 6 *a
  37975. // Face layout on texture UV mapping
  37976. // ============
  37977. // \ 4 /\ 16 / ======
  37978. // \ / \ / /\ 11 /
  37979. // \/ 7 \/ / \ /
  37980. // ======= / 10 \/
  37981. // /\ 17 /\ =======
  37982. // / \ / \ \ 15 /\
  37983. // / 8 \/ 12 \ \ / \
  37984. // ============ \/ 6 \
  37985. // \ 18 /\ ============
  37986. // \ / \ \ 5 /\ 0 /
  37987. // \/ 13 \ \ / \ /
  37988. // ======= \/ 1 \/
  37989. // =============
  37990. // /\ 19 /\ 2 /\
  37991. // / \ / \ / \
  37992. // / 14 \/ 9 \/ 3 \
  37993. // ===================
  37994. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37995. var ustep = 138 / 1024;
  37996. var vstep = 239 / 1024;
  37997. var uoffset = 60 / 1024;
  37998. var voffset = 26 / 1024;
  37999. // Second island should have margin, not to touch the first island
  38000. // avoid any borderline artefact in pixel rounding
  38001. var island_u_offset = -40 / 1024;
  38002. var island_v_offset = +20 / 1024;
  38003. // face is either island 0 or 1 :
  38004. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38005. var island = [
  38006. 0, 0, 0, 0, 1,
  38007. 0, 0, 1, 1, 0,
  38008. 0, 0, 1, 1, 0,
  38009. 0, 1, 1, 1, 0 // 15 - 19
  38010. ];
  38011. var indices = new Array();
  38012. var positions = new Array();
  38013. var normals = new Array();
  38014. var uvs = new Array();
  38015. var current_indice = 0;
  38016. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38017. var face_vertex_pos = new Array(3);
  38018. var face_vertex_uv = new Array(3);
  38019. var v012;
  38020. for (v012 = 0; v012 < 3; v012++) {
  38021. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38022. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38023. }
  38024. // create all with normals
  38025. for (var face = 0; face < 20; face++) {
  38026. // 3 vertex per face
  38027. for (v012 = 0; v012 < 3; v012++) {
  38028. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38029. var v_id = ico_indices[3 * face + v012];
  38030. // vertex have 3D position (x,y,z)
  38031. 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]);
  38032. // Normalize to get normal, then scale to radius
  38033. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38034. // uv Coordinates from vertex ID
  38035. 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);
  38036. }
  38037. // Subdivide the face (interpolate pos, norm, uv)
  38038. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38039. // - norm is linear interpolation of vertex corner normal
  38040. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38041. // - uv is linear interpolation
  38042. //
  38043. // Topology is as below for sub-divide by 2
  38044. // vertex shown as v0,v1,v2
  38045. // interp index is i1 to progress in range [v0,v1[
  38046. // interp index is i2 to progress in range [v0,v2[
  38047. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38048. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38049. //
  38050. //
  38051. // i2 v2
  38052. // ^ ^
  38053. // / / \
  38054. // / / \
  38055. // / / \
  38056. // / / (0,1) \
  38057. // / #---------\
  38058. // / / \ (0,0)'/ \
  38059. // / / \ / \
  38060. // / / \ / \
  38061. // / / (0,0) \ / (1,0) \
  38062. // / #---------#---------\
  38063. // v0 v1
  38064. //
  38065. // --------------------> i1
  38066. //
  38067. // interp of (i1,i2):
  38068. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38069. // along i1 : lerp(x0,x1, i1/(S-i2))
  38070. //
  38071. // centroid of triangle is needed to get help normal computation
  38072. // (c1,c2) are used for centroid location
  38073. var interp_vertex = function (i1, i2, c1, c2) {
  38074. // vertex is interpolated from
  38075. // - face_vertex_pos[0..2]
  38076. // - face_vertex_uv[0..2]
  38077. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38078. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38079. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38080. pos_interp.normalize();
  38081. var vertex_normal;
  38082. if (flat) {
  38083. // in flat mode, recalculate normal as face centroid normal
  38084. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38085. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38086. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38087. }
  38088. else {
  38089. // in smooth mode, recalculate normal from each single vertex position
  38090. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38091. }
  38092. // Vertex normal need correction due to X,Y,Z radius scaling
  38093. vertex_normal.x /= radiusX;
  38094. vertex_normal.y /= radiusY;
  38095. vertex_normal.z /= radiusZ;
  38096. vertex_normal.normalize();
  38097. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38098. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38099. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38100. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38101. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38102. uvs.push(uv_interp.x, uv_interp.y);
  38103. // push each vertex has member of a face
  38104. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38105. indices.push(current_indice);
  38106. current_indice++;
  38107. };
  38108. for (var i2 = 0; i2 < subdivisions; i2++) {
  38109. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38110. // face : (i1,i2) for /\ :
  38111. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38112. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38113. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38114. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38115. if (i1 + i2 + 1 < subdivisions) {
  38116. // face : (i1,i2)' for \/ :
  38117. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38118. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38119. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38120. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38121. }
  38122. }
  38123. }
  38124. }
  38125. // Sides
  38126. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38127. // Result
  38128. var vertexData = new VertexData();
  38129. vertexData.indices = indices;
  38130. vertexData.positions = positions;
  38131. vertexData.normals = normals;
  38132. vertexData.uvs = uvs;
  38133. return vertexData;
  38134. };
  38135. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38136. /**
  38137. * Creates the VertexData for a Polyhedron
  38138. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38139. * * type provided types are:
  38140. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38141. * * 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)
  38142. * * size the size of the IcoSphere, optional default 1
  38143. * * sizeX allows stretching in the x direction, optional, default size
  38144. * * sizeY allows stretching in the y direction, optional, default size
  38145. * * sizeZ allows stretching in the z direction, optional, default size
  38146. * * 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
  38147. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38148. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38149. * * flat when true creates a flat shaded mesh, optional, default true
  38150. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38151. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38152. * * 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)
  38153. * * 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)
  38154. * @returns the VertexData of the Polyhedron
  38155. */
  38156. VertexData.CreatePolyhedron = function (options) {
  38157. // provided polyhedron types :
  38158. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38159. // 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)
  38160. var polyhedra = [];
  38161. 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]] };
  38162. 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]] };
  38163. polyhedra[2] = {
  38164. 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]],
  38165. 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]]
  38166. };
  38167. polyhedra[3] = {
  38168. 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]],
  38169. 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]]
  38170. };
  38171. polyhedra[4] = {
  38172. 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]],
  38173. 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]]
  38174. };
  38175. 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]] };
  38176. 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]] };
  38177. 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]] };
  38178. 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]] };
  38179. 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]] };
  38180. 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]] };
  38181. 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]] };
  38182. 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]] };
  38183. 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]] };
  38184. polyhedra[14] = {
  38185. 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]],
  38186. 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]]
  38187. };
  38188. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38189. var size = options.size;
  38190. var sizeX = options.sizeX || size || 1;
  38191. var sizeY = options.sizeY || size || 1;
  38192. var sizeZ = options.sizeZ || size || 1;
  38193. var data = options.custom || polyhedra[type];
  38194. var nbfaces = data.face.length;
  38195. var faceUV = options.faceUV || new Array(nbfaces);
  38196. var faceColors = options.faceColors;
  38197. var flat = (options.flat === undefined) ? true : options.flat;
  38198. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38199. var positions = new Array();
  38200. var indices = new Array();
  38201. var normals = new Array();
  38202. var uvs = new Array();
  38203. var colors = new Array();
  38204. var index = 0;
  38205. var faceIdx = 0; // face cursor in the array "indexes"
  38206. var indexes = new Array();
  38207. var i = 0;
  38208. var f = 0;
  38209. var u, v, ang, x, y, tmp;
  38210. // default face colors and UV if undefined
  38211. if (flat) {
  38212. for (f = 0; f < nbfaces; f++) {
  38213. if (faceColors && faceColors[f] === undefined) {
  38214. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38215. }
  38216. if (faceUV && faceUV[f] === undefined) {
  38217. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38218. }
  38219. }
  38220. }
  38221. if (!flat) {
  38222. for (i = 0; i < data.vertex.length; i++) {
  38223. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38224. uvs.push(0, 0);
  38225. }
  38226. for (f = 0; f < nbfaces; f++) {
  38227. for (i = 0; i < data.face[f].length - 2; i++) {
  38228. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38229. }
  38230. }
  38231. }
  38232. else {
  38233. for (f = 0; f < nbfaces; f++) {
  38234. var fl = data.face[f].length; // number of vertices of the current face
  38235. ang = 2 * Math.PI / fl;
  38236. x = 0.5 * Math.tan(ang / 2);
  38237. y = 0.5;
  38238. // positions, uvs, colors
  38239. for (i = 0; i < fl; i++) {
  38240. // positions
  38241. 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);
  38242. indexes.push(index);
  38243. index++;
  38244. // uvs
  38245. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38246. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38247. uvs.push(u, v);
  38248. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38249. y = x * Math.sin(ang) + y * Math.cos(ang);
  38250. x = tmp;
  38251. // colors
  38252. if (faceColors) {
  38253. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38254. }
  38255. }
  38256. // indices from indexes
  38257. for (i = 0; i < fl - 2; i++) {
  38258. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38259. }
  38260. faceIdx += fl;
  38261. }
  38262. }
  38263. VertexData.ComputeNormals(positions, indices, normals);
  38264. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38265. var vertexData = new VertexData();
  38266. vertexData.positions = positions;
  38267. vertexData.indices = indices;
  38268. vertexData.normals = normals;
  38269. vertexData.uvs = uvs;
  38270. if (faceColors && flat) {
  38271. vertexData.colors = colors;
  38272. }
  38273. return vertexData;
  38274. };
  38275. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38276. /**
  38277. * Creates the VertexData for a TorusKnot
  38278. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38279. * * radius the radius of the torus knot, optional, default 2
  38280. * * tube the thickness of the tube, optional, default 0.5
  38281. * * radialSegments the number of sides on each tube segments, optional, default 32
  38282. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38283. * * p the number of windings around the z axis, optional, default 2
  38284. * * q the number of windings around the x axis, optional, default 3
  38285. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38286. * * 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)
  38287. * * 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)
  38288. * @returns the VertexData of the Torus Knot
  38289. */
  38290. VertexData.CreateTorusKnot = function (options) {
  38291. var indices = new Array();
  38292. var positions = new Array();
  38293. var normals = new Array();
  38294. var uvs = new Array();
  38295. var radius = options.radius || 2;
  38296. var tube = options.tube || 0.5;
  38297. var radialSegments = options.radialSegments || 32;
  38298. var tubularSegments = options.tubularSegments || 32;
  38299. var p = options.p || 2;
  38300. var q = options.q || 3;
  38301. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38302. // Helper
  38303. var getPos = function (angle) {
  38304. var cu = Math.cos(angle);
  38305. var su = Math.sin(angle);
  38306. var quOverP = q / p * angle;
  38307. var cs = Math.cos(quOverP);
  38308. var tx = radius * (2 + cs) * 0.5 * cu;
  38309. var ty = radius * (2 + cs) * su * 0.5;
  38310. var tz = radius * Math.sin(quOverP) * 0.5;
  38311. return new BABYLON.Vector3(tx, ty, tz);
  38312. };
  38313. // Vertices
  38314. var i;
  38315. var j;
  38316. for (i = 0; i <= radialSegments; i++) {
  38317. var modI = i % radialSegments;
  38318. var u = modI / radialSegments * 2 * p * Math.PI;
  38319. var p1 = getPos(u);
  38320. var p2 = getPos(u + 0.01);
  38321. var tang = p2.subtract(p1);
  38322. var n = p2.add(p1);
  38323. var bitan = BABYLON.Vector3.Cross(tang, n);
  38324. n = BABYLON.Vector3.Cross(bitan, tang);
  38325. bitan.normalize();
  38326. n.normalize();
  38327. for (j = 0; j < tubularSegments; j++) {
  38328. var modJ = j % tubularSegments;
  38329. var v = modJ / tubularSegments * 2 * Math.PI;
  38330. var cx = -tube * Math.cos(v);
  38331. var cy = tube * Math.sin(v);
  38332. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38333. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38334. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38335. uvs.push(i / radialSegments);
  38336. uvs.push(j / tubularSegments);
  38337. }
  38338. }
  38339. for (i = 0; i < radialSegments; i++) {
  38340. for (j = 0; j < tubularSegments; j++) {
  38341. var jNext = (j + 1) % tubularSegments;
  38342. var a = i * tubularSegments + j;
  38343. var b = (i + 1) * tubularSegments + j;
  38344. var c = (i + 1) * tubularSegments + jNext;
  38345. var d = i * tubularSegments + jNext;
  38346. indices.push(d);
  38347. indices.push(b);
  38348. indices.push(a);
  38349. indices.push(d);
  38350. indices.push(c);
  38351. indices.push(b);
  38352. }
  38353. }
  38354. // Normals
  38355. VertexData.ComputeNormals(positions, indices, normals);
  38356. // Sides
  38357. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38358. // Result
  38359. var vertexData = new VertexData();
  38360. vertexData.indices = indices;
  38361. vertexData.positions = positions;
  38362. vertexData.normals = normals;
  38363. vertexData.uvs = uvs;
  38364. return vertexData;
  38365. };
  38366. // Tools
  38367. /**
  38368. * Compute normals for given positions and indices
  38369. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38370. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38371. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38372. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38373. * * facetNormals : optional array of facet normals (vector3)
  38374. * * facetPositions : optional array of facet positions (vector3)
  38375. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38376. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38377. * * bInfo : optional bounding info, required for facetPartitioning computation
  38378. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38379. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38380. * * useRightHandedSystem: optional boolean to for right handed system computation
  38381. * * depthSort : optional boolean to enable the facet depth sort computation
  38382. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38383. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38384. */
  38385. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38386. // temporary scalar variables
  38387. var index = 0; // facet index
  38388. var p1p2x = 0.0; // p1p2 vector x coordinate
  38389. var p1p2y = 0.0; // p1p2 vector y coordinate
  38390. var p1p2z = 0.0; // p1p2 vector z coordinate
  38391. var p3p2x = 0.0; // p3p2 vector x coordinate
  38392. var p3p2y = 0.0; // p3p2 vector y coordinate
  38393. var p3p2z = 0.0; // p3p2 vector z coordinate
  38394. var faceNormalx = 0.0; // facet normal x coordinate
  38395. var faceNormaly = 0.0; // facet normal y coordinate
  38396. var faceNormalz = 0.0; // facet normal z coordinate
  38397. var length = 0.0; // facet normal length before normalization
  38398. var v1x = 0; // vector1 x index in the positions array
  38399. var v1y = 0; // vector1 y index in the positions array
  38400. var v1z = 0; // vector1 z index in the positions array
  38401. var v2x = 0; // vector2 x index in the positions array
  38402. var v2y = 0; // vector2 y index in the positions array
  38403. var v2z = 0; // vector2 z index in the positions array
  38404. var v3x = 0; // vector3 x index in the positions array
  38405. var v3y = 0; // vector3 y index in the positions array
  38406. var v3z = 0; // vector3 z index in the positions array
  38407. var computeFacetNormals = false;
  38408. var computeFacetPositions = false;
  38409. var computeFacetPartitioning = false;
  38410. var computeDepthSort = false;
  38411. var faceNormalSign = 1;
  38412. var ratio = 0;
  38413. var distanceTo = null;
  38414. if (options) {
  38415. computeFacetNormals = (options.facetNormals) ? true : false;
  38416. computeFacetPositions = (options.facetPositions) ? true : false;
  38417. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38418. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38419. ratio = options.ratio || 0;
  38420. computeDepthSort = (options.depthSort) ? true : false;
  38421. distanceTo = (options.distanceTo);
  38422. if (computeDepthSort) {
  38423. if (distanceTo === undefined) {
  38424. distanceTo = BABYLON.Vector3.Zero();
  38425. }
  38426. var depthSortedFacets = options.depthSortedFacets;
  38427. }
  38428. }
  38429. // facetPartitioning reinit if needed
  38430. var xSubRatio = 0;
  38431. var ySubRatio = 0;
  38432. var zSubRatio = 0;
  38433. var subSq = 0;
  38434. if (computeFacetPartitioning && options && options.bbSize) {
  38435. var ox = 0; // X partitioning index for facet position
  38436. var oy = 0; // Y partinioning index for facet position
  38437. var oz = 0; // Z partinioning index for facet position
  38438. var b1x = 0; // X partitioning index for facet v1 vertex
  38439. var b1y = 0; // Y partitioning index for facet v1 vertex
  38440. var b1z = 0; // z partitioning index for facet v1 vertex
  38441. var b2x = 0; // X partitioning index for facet v2 vertex
  38442. var b2y = 0; // Y partitioning index for facet v2 vertex
  38443. var b2z = 0; // Z partitioning index for facet v2 vertex
  38444. var b3x = 0; // X partitioning index for facet v3 vertex
  38445. var b3y = 0; // Y partitioning index for facet v3 vertex
  38446. var b3z = 0; // Z partitioning index for facet v3 vertex
  38447. var block_idx_o = 0; // facet barycenter block index
  38448. var block_idx_v1 = 0; // v1 vertex block index
  38449. var block_idx_v2 = 0; // v2 vertex block index
  38450. var block_idx_v3 = 0; // v3 vertex block index
  38451. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38452. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38453. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38454. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38455. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38456. subSq = options.subDiv.max * options.subDiv.max;
  38457. options.facetPartitioning.length = 0;
  38458. }
  38459. // reset the normals
  38460. for (index = 0; index < positions.length; index++) {
  38461. normals[index] = 0.0;
  38462. }
  38463. // Loop : 1 indice triplet = 1 facet
  38464. var nbFaces = (indices.length / 3) | 0;
  38465. for (index = 0; index < nbFaces; index++) {
  38466. // get the indexes of the coordinates of each vertex of the facet
  38467. v1x = indices[index * 3] * 3;
  38468. v1y = v1x + 1;
  38469. v1z = v1x + 2;
  38470. v2x = indices[index * 3 + 1] * 3;
  38471. v2y = v2x + 1;
  38472. v2z = v2x + 2;
  38473. v3x = indices[index * 3 + 2] * 3;
  38474. v3y = v3x + 1;
  38475. v3z = v3x + 2;
  38476. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38477. p1p2y = positions[v1y] - positions[v2y];
  38478. p1p2z = positions[v1z] - positions[v2z];
  38479. p3p2x = positions[v3x] - positions[v2x];
  38480. p3p2y = positions[v3y] - positions[v2y];
  38481. p3p2z = positions[v3z] - positions[v2z];
  38482. // compute the face normal with the cross product
  38483. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38484. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38485. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38486. // normalize this normal and store it in the array facetData
  38487. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38488. length = (length === 0) ? 1.0 : length;
  38489. faceNormalx /= length;
  38490. faceNormaly /= length;
  38491. faceNormalz /= length;
  38492. if (computeFacetNormals && options) {
  38493. options.facetNormals[index].x = faceNormalx;
  38494. options.facetNormals[index].y = faceNormaly;
  38495. options.facetNormals[index].z = faceNormalz;
  38496. }
  38497. if (computeFacetPositions && options) {
  38498. // compute and the facet barycenter coordinates in the array facetPositions
  38499. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38500. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38501. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38502. }
  38503. if (computeFacetPartitioning && options) {
  38504. // store the facet indexes in arrays in the main facetPartitioning array :
  38505. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38506. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38507. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38508. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38509. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38510. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38511. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38512. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38513. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38514. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38515. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38516. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38517. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38518. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38519. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38520. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38521. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38522. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38523. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38524. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38525. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38526. // push each facet index in each block containing the vertex
  38527. options.facetPartitioning[block_idx_v1].push(index);
  38528. if (block_idx_v2 != block_idx_v1) {
  38529. options.facetPartitioning[block_idx_v2].push(index);
  38530. }
  38531. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38532. options.facetPartitioning[block_idx_v3].push(index);
  38533. }
  38534. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38535. options.facetPartitioning[block_idx_o].push(index);
  38536. }
  38537. }
  38538. if (computeDepthSort && options && options.facetPositions) {
  38539. var dsf = depthSortedFacets[index];
  38540. dsf.ind = index * 3;
  38541. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38542. }
  38543. // compute the normals anyway
  38544. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38545. normals[v1y] += faceNormaly;
  38546. normals[v1z] += faceNormalz;
  38547. normals[v2x] += faceNormalx;
  38548. normals[v2y] += faceNormaly;
  38549. normals[v2z] += faceNormalz;
  38550. normals[v3x] += faceNormalx;
  38551. normals[v3y] += faceNormaly;
  38552. normals[v3z] += faceNormalz;
  38553. }
  38554. // last normalization of each normal
  38555. for (index = 0; index < normals.length / 3; index++) {
  38556. faceNormalx = normals[index * 3];
  38557. faceNormaly = normals[index * 3 + 1];
  38558. faceNormalz = normals[index * 3 + 2];
  38559. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38560. length = (length === 0) ? 1.0 : length;
  38561. faceNormalx /= length;
  38562. faceNormaly /= length;
  38563. faceNormalz /= length;
  38564. normals[index * 3] = faceNormalx;
  38565. normals[index * 3 + 1] = faceNormaly;
  38566. normals[index * 3 + 2] = faceNormalz;
  38567. }
  38568. };
  38569. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38570. var li = indices.length;
  38571. var ln = normals.length;
  38572. var i;
  38573. var n;
  38574. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38575. switch (sideOrientation) {
  38576. case BABYLON.Mesh.FRONTSIDE:
  38577. // nothing changed
  38578. break;
  38579. case BABYLON.Mesh.BACKSIDE:
  38580. var tmp;
  38581. // indices
  38582. for (i = 0; i < li; i += 3) {
  38583. tmp = indices[i];
  38584. indices[i] = indices[i + 2];
  38585. indices[i + 2] = tmp;
  38586. }
  38587. // normals
  38588. for (n = 0; n < ln; n++) {
  38589. normals[n] = -normals[n];
  38590. }
  38591. break;
  38592. case BABYLON.Mesh.DOUBLESIDE:
  38593. // positions
  38594. var lp = positions.length;
  38595. var l = lp / 3;
  38596. for (var p = 0; p < lp; p++) {
  38597. positions[lp + p] = positions[p];
  38598. }
  38599. // indices
  38600. for (i = 0; i < li; i += 3) {
  38601. indices[i + li] = indices[i + 2] + l;
  38602. indices[i + 1 + li] = indices[i + 1] + l;
  38603. indices[i + 2 + li] = indices[i] + l;
  38604. }
  38605. // normals
  38606. for (n = 0; n < ln; n++) {
  38607. normals[ln + n] = -normals[n];
  38608. }
  38609. // uvs
  38610. var lu = uvs.length;
  38611. var u = 0;
  38612. for (u = 0; u < lu; u++) {
  38613. uvs[u + lu] = uvs[u];
  38614. }
  38615. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38616. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38617. u = 0;
  38618. for (i = 0; i < lu / 2; i++) {
  38619. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38620. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38621. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38622. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38623. u += 2;
  38624. }
  38625. break;
  38626. }
  38627. };
  38628. /**
  38629. * Applies VertexData created from the imported parameters to the geometry
  38630. * @param parsedVertexData the parsed data from an imported file
  38631. * @param geometry the geometry to apply the VertexData to
  38632. */
  38633. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38634. var vertexData = new VertexData();
  38635. // positions
  38636. var positions = parsedVertexData.positions;
  38637. if (positions) {
  38638. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38639. }
  38640. // normals
  38641. var normals = parsedVertexData.normals;
  38642. if (normals) {
  38643. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38644. }
  38645. // tangents
  38646. var tangents = parsedVertexData.tangents;
  38647. if (tangents) {
  38648. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38649. }
  38650. // uvs
  38651. var uvs = parsedVertexData.uvs;
  38652. if (uvs) {
  38653. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38654. }
  38655. // uv2s
  38656. var uv2s = parsedVertexData.uv2s;
  38657. if (uv2s) {
  38658. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38659. }
  38660. // uv3s
  38661. var uv3s = parsedVertexData.uv3s;
  38662. if (uv3s) {
  38663. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38664. }
  38665. // uv4s
  38666. var uv4s = parsedVertexData.uv4s;
  38667. if (uv4s) {
  38668. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38669. }
  38670. // uv5s
  38671. var uv5s = parsedVertexData.uv5s;
  38672. if (uv5s) {
  38673. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38674. }
  38675. // uv6s
  38676. var uv6s = parsedVertexData.uv6s;
  38677. if (uv6s) {
  38678. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38679. }
  38680. // colors
  38681. var colors = parsedVertexData.colors;
  38682. if (colors) {
  38683. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38684. }
  38685. // matricesIndices
  38686. var matricesIndices = parsedVertexData.matricesIndices;
  38687. if (matricesIndices) {
  38688. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38689. }
  38690. // matricesWeights
  38691. var matricesWeights = parsedVertexData.matricesWeights;
  38692. if (matricesWeights) {
  38693. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38694. }
  38695. // indices
  38696. var indices = parsedVertexData.indices;
  38697. if (indices) {
  38698. vertexData.indices = indices;
  38699. }
  38700. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38701. };
  38702. return VertexData;
  38703. }());
  38704. BABYLON.VertexData = VertexData;
  38705. })(BABYLON || (BABYLON = {}));
  38706. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38707. var BABYLON;
  38708. (function (BABYLON) {
  38709. /**
  38710. * Class used to store geometry data (vertex buffers + index buffer)
  38711. */
  38712. var Geometry = /** @class */ (function () {
  38713. /**
  38714. * Creates a new geometry
  38715. * @param id defines the unique ID
  38716. * @param scene defines the hosting scene
  38717. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38718. * @param updatable defines if geometry must be updatable (false by default)
  38719. * @param mesh defines the mesh that will be associated with the geometry
  38720. */
  38721. function Geometry(id, scene, vertexData, updatable, mesh) {
  38722. if (updatable === void 0) { updatable = false; }
  38723. if (mesh === void 0) { mesh = null; }
  38724. /**
  38725. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38726. */
  38727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38728. this._totalVertices = 0;
  38729. this._isDisposed = false;
  38730. this._indexBufferIsUpdatable = false;
  38731. this.id = id;
  38732. this._engine = scene.getEngine();
  38733. this._meshes = [];
  38734. this._scene = scene;
  38735. //Init vertex buffer cache
  38736. this._vertexBuffers = {};
  38737. this._indices = [];
  38738. this._updatable = updatable;
  38739. // vertexData
  38740. if (vertexData) {
  38741. this.setAllVerticesData(vertexData, updatable);
  38742. }
  38743. else {
  38744. this._totalVertices = 0;
  38745. this._indices = [];
  38746. }
  38747. if (this._engine.getCaps().vertexArrayObject) {
  38748. this._vertexArrayObjects = {};
  38749. }
  38750. // applyToMesh
  38751. if (mesh) {
  38752. if (mesh.getClassName() === "LinesMesh") {
  38753. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38754. this._updateExtend();
  38755. }
  38756. this.applyToMesh(mesh);
  38757. mesh.computeWorldMatrix(true);
  38758. }
  38759. }
  38760. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38761. /**
  38762. * 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
  38763. */
  38764. get: function () {
  38765. return this._boundingBias;
  38766. },
  38767. /**
  38768. * 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
  38769. */
  38770. set: function (value) {
  38771. if (this._boundingBias && this._boundingBias.equals(value)) {
  38772. return;
  38773. }
  38774. this._boundingBias = value.clone();
  38775. this._updateBoundingInfo(true, null);
  38776. },
  38777. enumerable: true,
  38778. configurable: true
  38779. });
  38780. /**
  38781. * Static function used to attach a new empty geometry to a mesh
  38782. * @param mesh defines the mesh to attach the geometry to
  38783. * @returns the new {BABYLON.Geometry}
  38784. */
  38785. Geometry.CreateGeometryForMesh = function (mesh) {
  38786. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38787. geometry.applyToMesh(mesh);
  38788. return geometry;
  38789. };
  38790. Object.defineProperty(Geometry.prototype, "extend", {
  38791. /**
  38792. * Gets the current extend of the geometry
  38793. */
  38794. get: function () {
  38795. return this._extend;
  38796. },
  38797. enumerable: true,
  38798. configurable: true
  38799. });
  38800. /**
  38801. * Gets the hosting scene
  38802. * @returns the hosting {BABYLON.Scene}
  38803. */
  38804. Geometry.prototype.getScene = function () {
  38805. return this._scene;
  38806. };
  38807. /**
  38808. * Gets the hosting engine
  38809. * @returns the hosting {BABYLON.Engine}
  38810. */
  38811. Geometry.prototype.getEngine = function () {
  38812. return this._engine;
  38813. };
  38814. /**
  38815. * Defines if the geometry is ready to use
  38816. * @returns true if the geometry is ready to be used
  38817. */
  38818. Geometry.prototype.isReady = function () {
  38819. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38820. };
  38821. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38822. /**
  38823. * Gets a value indicating that the geometry should not be serialized
  38824. */
  38825. get: function () {
  38826. for (var index = 0; index < this._meshes.length; index++) {
  38827. if (!this._meshes[index].doNotSerialize) {
  38828. return false;
  38829. }
  38830. }
  38831. return true;
  38832. },
  38833. enumerable: true,
  38834. configurable: true
  38835. });
  38836. /** @hidden */
  38837. Geometry.prototype._rebuild = function () {
  38838. if (this._vertexArrayObjects) {
  38839. this._vertexArrayObjects = {};
  38840. }
  38841. // Index buffer
  38842. if (this._meshes.length !== 0 && this._indices) {
  38843. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38844. }
  38845. // Vertex buffers
  38846. for (var key in this._vertexBuffers) {
  38847. var vertexBuffer = this._vertexBuffers[key];
  38848. vertexBuffer._rebuild();
  38849. }
  38850. };
  38851. /**
  38852. * Affects all geometry data in one call
  38853. * @param vertexData defines the geometry data
  38854. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38855. */
  38856. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38857. vertexData.applyToGeometry(this, updatable);
  38858. this.notifyUpdate();
  38859. };
  38860. /**
  38861. * Set specific vertex data
  38862. * @param kind defines the data kind (Position, normal, etc...)
  38863. * @param data defines the vertex data to use
  38864. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38865. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38866. */
  38867. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38868. if (updatable === void 0) { updatable = false; }
  38869. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38870. this.setVerticesBuffer(buffer);
  38871. };
  38872. /**
  38873. * Removes a specific vertex data
  38874. * @param kind defines the data kind (Position, normal, etc...)
  38875. */
  38876. Geometry.prototype.removeVerticesData = function (kind) {
  38877. if (this._vertexBuffers[kind]) {
  38878. this._vertexBuffers[kind].dispose();
  38879. delete this._vertexBuffers[kind];
  38880. }
  38881. };
  38882. /**
  38883. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38884. * @param buffer defines the vertex buffer to use
  38885. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38886. */
  38887. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38888. if (totalVertices === void 0) { totalVertices = null; }
  38889. var kind = buffer.getKind();
  38890. if (this._vertexBuffers[kind]) {
  38891. this._vertexBuffers[kind].dispose();
  38892. }
  38893. this._vertexBuffers[kind] = buffer;
  38894. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38895. var data = buffer.getData();
  38896. if (totalVertices != null) {
  38897. this._totalVertices = totalVertices;
  38898. }
  38899. else {
  38900. if (data != null) {
  38901. this._totalVertices = data.length / (buffer.byteStride / 4);
  38902. }
  38903. }
  38904. this._updateExtend(data);
  38905. this._resetPointsArrayCache();
  38906. var meshes = this._meshes;
  38907. var numOfMeshes = meshes.length;
  38908. for (var index = 0; index < numOfMeshes; index++) {
  38909. var mesh = meshes[index];
  38910. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38911. mesh._createGlobalSubMesh(false);
  38912. mesh.computeWorldMatrix(true);
  38913. }
  38914. }
  38915. this.notifyUpdate(kind);
  38916. if (this._vertexArrayObjects) {
  38917. this._disposeVertexArrayObjects();
  38918. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38919. }
  38920. };
  38921. /**
  38922. * Update a specific vertex buffer
  38923. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38924. * It will do nothing if the buffer is not updatable
  38925. * @param kind defines the data kind (Position, normal, etc...)
  38926. * @param data defines the data to use
  38927. * @param offset defines the offset in the target buffer where to store the data
  38928. * @param useBytes set to true if the offset is in bytes
  38929. */
  38930. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38931. if (useBytes === void 0) { useBytes = false; }
  38932. var vertexBuffer = this.getVertexBuffer(kind);
  38933. if (!vertexBuffer) {
  38934. return;
  38935. }
  38936. vertexBuffer.updateDirectly(data, offset, useBytes);
  38937. this.notifyUpdate(kind);
  38938. };
  38939. /**
  38940. * Update a specific vertex buffer
  38941. * This function will create a new buffer if the current one is not updatable
  38942. * @param kind defines the data kind (Position, normal, etc...)
  38943. * @param data defines the data to use
  38944. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38945. */
  38946. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38947. if (updateExtends === void 0) { updateExtends = false; }
  38948. var vertexBuffer = this.getVertexBuffer(kind);
  38949. if (!vertexBuffer) {
  38950. return;
  38951. }
  38952. vertexBuffer.update(data);
  38953. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38954. this._updateBoundingInfo(updateExtends, data);
  38955. }
  38956. this.notifyUpdate(kind);
  38957. };
  38958. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38959. if (updateExtends) {
  38960. this._updateExtend(data);
  38961. }
  38962. var meshes = this._meshes;
  38963. var numOfMeshes = meshes.length;
  38964. this._resetPointsArrayCache();
  38965. for (var index = 0; index < numOfMeshes; index++) {
  38966. var mesh = meshes[index];
  38967. if (updateExtends) {
  38968. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38969. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38970. var subMesh = mesh.subMeshes[subIndex];
  38971. subMesh.refreshBoundingInfo();
  38972. }
  38973. }
  38974. }
  38975. };
  38976. /** @hidden */
  38977. Geometry.prototype._bind = function (effect, indexToBind) {
  38978. if (!effect) {
  38979. return;
  38980. }
  38981. if (indexToBind === undefined) {
  38982. indexToBind = this._indexBuffer;
  38983. }
  38984. var vbs = this.getVertexBuffers();
  38985. if (!vbs) {
  38986. return;
  38987. }
  38988. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38989. this._engine.bindBuffers(vbs, indexToBind, effect);
  38990. return;
  38991. }
  38992. // Using VAO
  38993. if (!this._vertexArrayObjects[effect.key]) {
  38994. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38995. }
  38996. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38997. };
  38998. /**
  38999. * Gets total number of vertices
  39000. * @returns the total number of vertices
  39001. */
  39002. Geometry.prototype.getTotalVertices = function () {
  39003. if (!this.isReady()) {
  39004. return 0;
  39005. }
  39006. return this._totalVertices;
  39007. };
  39008. /**
  39009. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39010. * @param kind defines the data kind (Position, normal, etc...)
  39011. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39012. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39013. * @returns a float array containing vertex data
  39014. */
  39015. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39016. var vertexBuffer = this.getVertexBuffer(kind);
  39017. if (!vertexBuffer) {
  39018. return null;
  39019. }
  39020. var data = vertexBuffer.getData();
  39021. if (!data) {
  39022. return null;
  39023. }
  39024. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39025. var count = this._totalVertices * vertexBuffer.getSize();
  39026. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39027. var copy_1 = new Array(count);
  39028. vertexBuffer.forEach(count, function (value, index) {
  39029. copy_1[index] = value;
  39030. });
  39031. return copy_1;
  39032. }
  39033. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39034. if (data instanceof Array) {
  39035. var offset = vertexBuffer.byteOffset / 4;
  39036. return BABYLON.Tools.Slice(data, offset, offset + count);
  39037. }
  39038. else if (data instanceof ArrayBuffer) {
  39039. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39040. }
  39041. else {
  39042. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39043. }
  39044. }
  39045. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39046. return BABYLON.Tools.Slice(data);
  39047. }
  39048. return data;
  39049. };
  39050. /**
  39051. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39052. * @param kind defines the data kind (Position, normal, etc...)
  39053. * @returns true if the vertex buffer with the specified kind is updatable
  39054. */
  39055. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39056. var vb = this._vertexBuffers[kind];
  39057. if (!vb) {
  39058. return false;
  39059. }
  39060. return vb.isUpdatable();
  39061. };
  39062. /**
  39063. * Gets a specific vertex buffer
  39064. * @param kind defines the data kind (Position, normal, etc...)
  39065. * @returns a {BABYLON.VertexBuffer}
  39066. */
  39067. Geometry.prototype.getVertexBuffer = function (kind) {
  39068. if (!this.isReady()) {
  39069. return null;
  39070. }
  39071. return this._vertexBuffers[kind];
  39072. };
  39073. /**
  39074. * Returns all vertex buffers
  39075. * @return an object holding all vertex buffers indexed by kind
  39076. */
  39077. Geometry.prototype.getVertexBuffers = function () {
  39078. if (!this.isReady()) {
  39079. return null;
  39080. }
  39081. return this._vertexBuffers;
  39082. };
  39083. /**
  39084. * Gets a boolean indicating if specific vertex buffer is present
  39085. * @param kind defines the data kind (Position, normal, etc...)
  39086. * @returns true if data is present
  39087. */
  39088. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39089. if (!this._vertexBuffers) {
  39090. if (this._delayInfo) {
  39091. return this._delayInfo.indexOf(kind) !== -1;
  39092. }
  39093. return false;
  39094. }
  39095. return this._vertexBuffers[kind] !== undefined;
  39096. };
  39097. /**
  39098. * Gets a list of all attached data kinds (Position, normal, etc...)
  39099. * @returns a list of string containing all kinds
  39100. */
  39101. Geometry.prototype.getVerticesDataKinds = function () {
  39102. var result = [];
  39103. var kind;
  39104. if (!this._vertexBuffers && this._delayInfo) {
  39105. for (kind in this._delayInfo) {
  39106. result.push(kind);
  39107. }
  39108. }
  39109. else {
  39110. for (kind in this._vertexBuffers) {
  39111. result.push(kind);
  39112. }
  39113. }
  39114. return result;
  39115. };
  39116. /**
  39117. * Update index buffer
  39118. * @param indices defines the indices to store in the index buffer
  39119. * @param offset defines the offset in the target buffer where to store the data
  39120. */
  39121. Geometry.prototype.updateIndices = function (indices, offset) {
  39122. if (!this._indexBuffer) {
  39123. return;
  39124. }
  39125. if (!this._indexBufferIsUpdatable) {
  39126. this.setIndices(indices, null, true);
  39127. }
  39128. else {
  39129. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39130. }
  39131. };
  39132. /**
  39133. * Creates a new index buffer
  39134. * @param indices defines the indices to store in the index buffer
  39135. * @param totalVertices defines the total number of vertices (could be null)
  39136. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39137. */
  39138. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39139. if (totalVertices === void 0) { totalVertices = null; }
  39140. if (updatable === void 0) { updatable = false; }
  39141. if (this._indexBuffer) {
  39142. this._engine._releaseBuffer(this._indexBuffer);
  39143. }
  39144. this._disposeVertexArrayObjects();
  39145. this._indices = indices;
  39146. this._indexBufferIsUpdatable = updatable;
  39147. if (this._meshes.length !== 0 && this._indices) {
  39148. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39149. }
  39150. if (totalVertices != undefined) { // including null and undefined
  39151. this._totalVertices = totalVertices;
  39152. }
  39153. var meshes = this._meshes;
  39154. var numOfMeshes = meshes.length;
  39155. for (var index = 0; index < numOfMeshes; index++) {
  39156. meshes[index]._createGlobalSubMesh(true);
  39157. }
  39158. this.notifyUpdate();
  39159. };
  39160. /**
  39161. * Return the total number of indices
  39162. * @returns the total number of indices
  39163. */
  39164. Geometry.prototype.getTotalIndices = function () {
  39165. if (!this.isReady()) {
  39166. return 0;
  39167. }
  39168. return this._indices.length;
  39169. };
  39170. /**
  39171. * Gets the index buffer array
  39172. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39173. * @returns the index buffer array
  39174. */
  39175. Geometry.prototype.getIndices = function (copyWhenShared) {
  39176. if (!this.isReady()) {
  39177. return null;
  39178. }
  39179. var orig = this._indices;
  39180. if (!copyWhenShared || this._meshes.length === 1) {
  39181. return orig;
  39182. }
  39183. else {
  39184. var len = orig.length;
  39185. var copy = [];
  39186. for (var i = 0; i < len; i++) {
  39187. copy.push(orig[i]);
  39188. }
  39189. return copy;
  39190. }
  39191. };
  39192. /**
  39193. * Gets the index buffer
  39194. * @return the index buffer
  39195. */
  39196. Geometry.prototype.getIndexBuffer = function () {
  39197. if (!this.isReady()) {
  39198. return null;
  39199. }
  39200. return this._indexBuffer;
  39201. };
  39202. /** @hidden */
  39203. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39204. if (effect === void 0) { effect = null; }
  39205. if (!effect || !this._vertexArrayObjects) {
  39206. return;
  39207. }
  39208. if (this._vertexArrayObjects[effect.key]) {
  39209. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39210. delete this._vertexArrayObjects[effect.key];
  39211. }
  39212. };
  39213. /**
  39214. * Release the associated resources for a specific mesh
  39215. * @param mesh defines the source mesh
  39216. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39217. */
  39218. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39219. var meshes = this._meshes;
  39220. var index = meshes.indexOf(mesh);
  39221. if (index === -1) {
  39222. return;
  39223. }
  39224. meshes.splice(index, 1);
  39225. mesh._geometry = null;
  39226. if (meshes.length === 0 && shouldDispose) {
  39227. this.dispose();
  39228. }
  39229. };
  39230. /**
  39231. * Apply current geometry to a given mesh
  39232. * @param mesh defines the mesh to apply geometry to
  39233. */
  39234. Geometry.prototype.applyToMesh = function (mesh) {
  39235. if (mesh._geometry === this) {
  39236. return;
  39237. }
  39238. var previousGeometry = mesh._geometry;
  39239. if (previousGeometry) {
  39240. previousGeometry.releaseForMesh(mesh);
  39241. }
  39242. var meshes = this._meshes;
  39243. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39244. mesh._geometry = this;
  39245. this._scene.pushGeometry(this);
  39246. meshes.push(mesh);
  39247. if (this.isReady()) {
  39248. this._applyToMesh(mesh);
  39249. }
  39250. else {
  39251. mesh._boundingInfo = this._boundingInfo;
  39252. }
  39253. };
  39254. Geometry.prototype._updateExtend = function (data) {
  39255. if (data === void 0) { data = null; }
  39256. if (!data) {
  39257. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39258. }
  39259. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39260. };
  39261. Geometry.prototype._applyToMesh = function (mesh) {
  39262. var numOfMeshes = this._meshes.length;
  39263. // vertexBuffers
  39264. for (var kind in this._vertexBuffers) {
  39265. if (numOfMeshes === 1) {
  39266. this._vertexBuffers[kind].create();
  39267. }
  39268. var buffer = this._vertexBuffers[kind].getBuffer();
  39269. if (buffer)
  39270. buffer.references = numOfMeshes;
  39271. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39272. if (!this._extend) {
  39273. this._updateExtend();
  39274. }
  39275. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39276. mesh._createGlobalSubMesh(false);
  39277. //bounding info was just created again, world matrix should be applied again.
  39278. mesh._updateBoundingInfo();
  39279. }
  39280. }
  39281. // indexBuffer
  39282. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39283. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39284. }
  39285. if (this._indexBuffer) {
  39286. this._indexBuffer.references = numOfMeshes;
  39287. }
  39288. };
  39289. Geometry.prototype.notifyUpdate = function (kind) {
  39290. if (this.onGeometryUpdated) {
  39291. this.onGeometryUpdated(this, kind);
  39292. }
  39293. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39294. var mesh = _a[_i];
  39295. mesh._markSubMeshesAsAttributesDirty();
  39296. }
  39297. };
  39298. /**
  39299. * Load the geometry if it was flagged as delay loaded
  39300. * @param scene defines the hosting scene
  39301. * @param onLoaded defines a callback called when the geometry is loaded
  39302. */
  39303. Geometry.prototype.load = function (scene, onLoaded) {
  39304. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39305. return;
  39306. }
  39307. if (this.isReady()) {
  39308. if (onLoaded) {
  39309. onLoaded();
  39310. }
  39311. return;
  39312. }
  39313. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39314. this._queueLoad(scene, onLoaded);
  39315. };
  39316. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39317. var _this = this;
  39318. if (!this.delayLoadingFile) {
  39319. return;
  39320. }
  39321. scene._addPendingData(this);
  39322. scene._loadFile(this.delayLoadingFile, function (data) {
  39323. if (!_this._delayLoadingFunction) {
  39324. return;
  39325. }
  39326. _this._delayLoadingFunction(JSON.parse(data), _this);
  39327. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39328. _this._delayInfo = [];
  39329. scene._removePendingData(_this);
  39330. var meshes = _this._meshes;
  39331. var numOfMeshes = meshes.length;
  39332. for (var index = 0; index < numOfMeshes; index++) {
  39333. _this._applyToMesh(meshes[index]);
  39334. }
  39335. if (onLoaded) {
  39336. onLoaded();
  39337. }
  39338. }, undefined, true);
  39339. };
  39340. /**
  39341. * Invert the geometry to move from a right handed system to a left handed one.
  39342. */
  39343. Geometry.prototype.toLeftHanded = function () {
  39344. // Flip faces
  39345. var tIndices = this.getIndices(false);
  39346. if (tIndices != null && tIndices.length > 0) {
  39347. for (var i = 0; i < tIndices.length; i += 3) {
  39348. var tTemp = tIndices[i + 0];
  39349. tIndices[i + 0] = tIndices[i + 2];
  39350. tIndices[i + 2] = tTemp;
  39351. }
  39352. this.setIndices(tIndices);
  39353. }
  39354. // Negate position.z
  39355. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39356. if (tPositions != null && tPositions.length > 0) {
  39357. for (var i = 0; i < tPositions.length; i += 3) {
  39358. tPositions[i + 2] = -tPositions[i + 2];
  39359. }
  39360. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39361. }
  39362. // Negate normal.z
  39363. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39364. if (tNormals != null && tNormals.length > 0) {
  39365. for (var i = 0; i < tNormals.length; i += 3) {
  39366. tNormals[i + 2] = -tNormals[i + 2];
  39367. }
  39368. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39369. }
  39370. };
  39371. // Cache
  39372. /** @hidden */
  39373. Geometry.prototype._resetPointsArrayCache = function () {
  39374. this._positions = null;
  39375. };
  39376. /** @hidden */
  39377. Geometry.prototype._generatePointsArray = function () {
  39378. if (this._positions)
  39379. return true;
  39380. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39381. if (!data || data.length === 0) {
  39382. return false;
  39383. }
  39384. this._positions = [];
  39385. for (var index = 0; index < data.length; index += 3) {
  39386. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39387. }
  39388. return true;
  39389. };
  39390. /**
  39391. * Gets a value indicating if the geometry is disposed
  39392. * @returns true if the geometry was disposed
  39393. */
  39394. Geometry.prototype.isDisposed = function () {
  39395. return this._isDisposed;
  39396. };
  39397. Geometry.prototype._disposeVertexArrayObjects = function () {
  39398. if (this._vertexArrayObjects) {
  39399. for (var kind in this._vertexArrayObjects) {
  39400. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39401. }
  39402. this._vertexArrayObjects = {};
  39403. }
  39404. };
  39405. /**
  39406. * Free all associated resources
  39407. */
  39408. Geometry.prototype.dispose = function () {
  39409. var meshes = this._meshes;
  39410. var numOfMeshes = meshes.length;
  39411. var index;
  39412. for (index = 0; index < numOfMeshes; index++) {
  39413. this.releaseForMesh(meshes[index]);
  39414. }
  39415. this._meshes = [];
  39416. this._disposeVertexArrayObjects();
  39417. for (var kind in this._vertexBuffers) {
  39418. this._vertexBuffers[kind].dispose();
  39419. }
  39420. this._vertexBuffers = {};
  39421. this._totalVertices = 0;
  39422. if (this._indexBuffer) {
  39423. this._engine._releaseBuffer(this._indexBuffer);
  39424. }
  39425. this._indexBuffer = null;
  39426. this._indices = [];
  39427. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39428. this.delayLoadingFile = null;
  39429. this._delayLoadingFunction = null;
  39430. this._delayInfo = [];
  39431. this._boundingInfo = null;
  39432. this._scene.removeGeometry(this);
  39433. this._isDisposed = true;
  39434. };
  39435. /**
  39436. * Clone the current geometry into a new geometry
  39437. * @param id defines the unique ID of the new geometry
  39438. * @returns a new geometry object
  39439. */
  39440. Geometry.prototype.copy = function (id) {
  39441. var vertexData = new BABYLON.VertexData();
  39442. vertexData.indices = [];
  39443. var indices = this.getIndices();
  39444. if (indices) {
  39445. for (var index = 0; index < indices.length; index++) {
  39446. vertexData.indices.push(indices[index]);
  39447. }
  39448. }
  39449. var updatable = false;
  39450. var stopChecking = false;
  39451. var kind;
  39452. for (kind in this._vertexBuffers) {
  39453. // using slice() to make a copy of the array and not just reference it
  39454. var data = this.getVerticesData(kind);
  39455. if (data instanceof Float32Array) {
  39456. vertexData.set(new Float32Array(data), kind);
  39457. }
  39458. else {
  39459. vertexData.set(data.slice(0), kind);
  39460. }
  39461. if (!stopChecking) {
  39462. var vb = this.getVertexBuffer(kind);
  39463. if (vb) {
  39464. updatable = vb.isUpdatable();
  39465. stopChecking = !updatable;
  39466. }
  39467. }
  39468. }
  39469. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39470. geometry.delayLoadState = this.delayLoadState;
  39471. geometry.delayLoadingFile = this.delayLoadingFile;
  39472. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39473. for (kind in this._delayInfo) {
  39474. geometry._delayInfo = geometry._delayInfo || [];
  39475. geometry._delayInfo.push(kind);
  39476. }
  39477. // Bounding info
  39478. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39479. return geometry;
  39480. };
  39481. /**
  39482. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39483. * @return a JSON representation of the current geometry data (without the vertices data)
  39484. */
  39485. Geometry.prototype.serialize = function () {
  39486. var serializationObject = {};
  39487. serializationObject.id = this.id;
  39488. serializationObject.updatable = this._updatable;
  39489. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39490. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39491. }
  39492. return serializationObject;
  39493. };
  39494. Geometry.prototype.toNumberArray = function (origin) {
  39495. if (Array.isArray(origin)) {
  39496. return origin;
  39497. }
  39498. else {
  39499. return Array.prototype.slice.call(origin);
  39500. }
  39501. };
  39502. /**
  39503. * Serialize all vertices data into a JSON oject
  39504. * @returns a JSON representation of the current geometry data
  39505. */
  39506. Geometry.prototype.serializeVerticeData = function () {
  39507. var serializationObject = this.serialize();
  39508. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39509. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39510. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39511. serializationObject.positions._updatable = true;
  39512. }
  39513. }
  39514. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39515. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39516. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39517. serializationObject.normals._updatable = true;
  39518. }
  39519. }
  39520. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39521. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39522. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39523. serializationObject.tangets._updatable = true;
  39524. }
  39525. }
  39526. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39527. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39528. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39529. serializationObject.uvs._updatable = true;
  39530. }
  39531. }
  39532. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39533. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39534. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39535. serializationObject.uv2s._updatable = true;
  39536. }
  39537. }
  39538. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39539. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39540. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39541. serializationObject.uv3s._updatable = true;
  39542. }
  39543. }
  39544. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39545. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39546. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39547. serializationObject.uv4s._updatable = true;
  39548. }
  39549. }
  39550. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39551. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39552. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39553. serializationObject.uv5s._updatable = true;
  39554. }
  39555. }
  39556. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39557. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39558. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39559. serializationObject.uv6s._updatable = true;
  39560. }
  39561. }
  39562. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39563. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39564. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39565. serializationObject.colors._updatable = true;
  39566. }
  39567. }
  39568. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39569. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39570. serializationObject.matricesIndices._isExpanded = true;
  39571. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39572. serializationObject.matricesIndices._updatable = true;
  39573. }
  39574. }
  39575. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39576. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39577. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39578. serializationObject.matricesWeights._updatable = true;
  39579. }
  39580. }
  39581. serializationObject.indices = this.toNumberArray(this.getIndices());
  39582. return serializationObject;
  39583. };
  39584. // Statics
  39585. /**
  39586. * Extracts a clone of a mesh geometry
  39587. * @param mesh defines the source mesh
  39588. * @param id defines the unique ID of the new geometry object
  39589. * @returns the new geometry object
  39590. */
  39591. Geometry.ExtractFromMesh = function (mesh, id) {
  39592. var geometry = mesh._geometry;
  39593. if (!geometry) {
  39594. return null;
  39595. }
  39596. return geometry.copy(id);
  39597. };
  39598. /**
  39599. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39600. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39601. * Be aware Math.random() could cause collisions, but:
  39602. * "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"
  39603. * @returns a string containing a new GUID
  39604. */
  39605. Geometry.RandomId = function () {
  39606. return BABYLON.Tools.RandomId();
  39607. };
  39608. /** @hidden */
  39609. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39610. var scene = mesh.getScene();
  39611. // Geometry
  39612. var geometryId = parsedGeometry.geometryId;
  39613. if (geometryId) {
  39614. var geometry = scene.getGeometryByID(geometryId);
  39615. if (geometry) {
  39616. geometry.applyToMesh(mesh);
  39617. }
  39618. }
  39619. else if (parsedGeometry instanceof ArrayBuffer) {
  39620. var binaryInfo = mesh._binaryInfo;
  39621. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39622. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39623. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39624. }
  39625. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39626. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39627. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39628. }
  39629. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39630. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39631. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39632. }
  39633. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39634. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39635. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39636. }
  39637. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39638. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39639. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39640. }
  39641. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39642. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39643. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39644. }
  39645. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39646. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39647. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39648. }
  39649. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39650. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39651. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39652. }
  39653. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39654. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39655. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39656. }
  39657. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39658. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39659. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39660. }
  39661. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39662. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39663. var floatIndices = [];
  39664. for (var i = 0; i < matricesIndicesData.length; i++) {
  39665. var index = matricesIndicesData[i];
  39666. floatIndices.push(index & 0x000000FF);
  39667. floatIndices.push((index & 0x0000FF00) >> 8);
  39668. floatIndices.push((index & 0x00FF0000) >> 16);
  39669. floatIndices.push(index >> 24);
  39670. }
  39671. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39672. }
  39673. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39674. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39675. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39676. }
  39677. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39678. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39679. mesh.setIndices(indicesData, null);
  39680. }
  39681. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39682. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39683. mesh.subMeshes = [];
  39684. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39685. var materialIndex = subMeshesData[(i * 5) + 0];
  39686. var verticesStart = subMeshesData[(i * 5) + 1];
  39687. var verticesCount = subMeshesData[(i * 5) + 2];
  39688. var indexStart = subMeshesData[(i * 5) + 3];
  39689. var indexCount = subMeshesData[(i * 5) + 4];
  39690. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39691. }
  39692. }
  39693. }
  39694. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39695. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39696. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39697. if (parsedGeometry.tangents) {
  39698. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39699. }
  39700. if (parsedGeometry.uvs) {
  39701. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39702. }
  39703. if (parsedGeometry.uvs2) {
  39704. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39705. }
  39706. if (parsedGeometry.uvs3) {
  39707. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39708. }
  39709. if (parsedGeometry.uvs4) {
  39710. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39711. }
  39712. if (parsedGeometry.uvs5) {
  39713. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39714. }
  39715. if (parsedGeometry.uvs6) {
  39716. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39717. }
  39718. if (parsedGeometry.colors) {
  39719. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39720. }
  39721. if (parsedGeometry.matricesIndices) {
  39722. if (!parsedGeometry.matricesIndices._isExpanded) {
  39723. var floatIndices = [];
  39724. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39725. var matricesIndex = parsedGeometry.matricesIndices[i];
  39726. floatIndices.push(matricesIndex & 0x000000FF);
  39727. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39728. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39729. floatIndices.push(matricesIndex >> 24);
  39730. }
  39731. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39732. }
  39733. else {
  39734. delete parsedGeometry.matricesIndices._isExpanded;
  39735. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39736. }
  39737. }
  39738. if (parsedGeometry.matricesIndicesExtra) {
  39739. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39740. var floatIndices = [];
  39741. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39742. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39743. floatIndices.push(matricesIndex & 0x000000FF);
  39744. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39745. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39746. floatIndices.push(matricesIndex >> 24);
  39747. }
  39748. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39749. }
  39750. else {
  39751. delete parsedGeometry.matricesIndices._isExpanded;
  39752. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39753. }
  39754. }
  39755. if (parsedGeometry.matricesWeights) {
  39756. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39757. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39758. }
  39759. if (parsedGeometry.matricesWeightsExtra) {
  39760. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39761. }
  39762. mesh.setIndices(parsedGeometry.indices, null);
  39763. }
  39764. // SubMeshes
  39765. if (parsedGeometry.subMeshes) {
  39766. mesh.subMeshes = [];
  39767. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39768. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39769. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39770. }
  39771. }
  39772. // Flat shading
  39773. if (mesh._shouldGenerateFlatShading) {
  39774. mesh.convertToFlatShadedMesh();
  39775. delete mesh._shouldGenerateFlatShading;
  39776. }
  39777. // Update
  39778. mesh.computeWorldMatrix(true);
  39779. // Octree
  39780. var sceneOctree = scene.selectionOctree;
  39781. if (sceneOctree !== undefined && sceneOctree !== null) {
  39782. sceneOctree.addMesh(mesh);
  39783. }
  39784. };
  39785. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39786. var epsilon = 1e-3;
  39787. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39788. return;
  39789. }
  39790. var noInfluenceBoneIndex = 0.0;
  39791. if (parsedGeometry.skeletonId > -1) {
  39792. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39793. if (!skeleton) {
  39794. return;
  39795. }
  39796. noInfluenceBoneIndex = skeleton.bones.length;
  39797. }
  39798. else {
  39799. return;
  39800. }
  39801. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39802. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39803. var matricesWeights = parsedGeometry.matricesWeights;
  39804. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39805. var influencers = parsedGeometry.numBoneInfluencer;
  39806. var size = matricesWeights.length;
  39807. for (var i = 0; i < size; i += 4) {
  39808. var weight = 0.0;
  39809. var firstZeroWeight = -1;
  39810. for (var j = 0; j < 4; j++) {
  39811. var w = matricesWeights[i + j];
  39812. weight += w;
  39813. if (w < epsilon && firstZeroWeight < 0) {
  39814. firstZeroWeight = j;
  39815. }
  39816. }
  39817. if (matricesWeightsExtra) {
  39818. for (var j = 0; j < 4; j++) {
  39819. var w = matricesWeightsExtra[i + j];
  39820. weight += w;
  39821. if (w < epsilon && firstZeroWeight < 0) {
  39822. firstZeroWeight = j + 4;
  39823. }
  39824. }
  39825. }
  39826. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39827. firstZeroWeight = influencers - 1;
  39828. }
  39829. if (weight > epsilon) {
  39830. var mweight = 1.0 / weight;
  39831. for (var j = 0; j < 4; j++) {
  39832. matricesWeights[i + j] *= mweight;
  39833. }
  39834. if (matricesWeightsExtra) {
  39835. for (var j = 0; j < 4; j++) {
  39836. matricesWeightsExtra[i + j] *= mweight;
  39837. }
  39838. }
  39839. }
  39840. else {
  39841. if (firstZeroWeight >= 4) {
  39842. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39843. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39844. }
  39845. else {
  39846. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39847. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39848. }
  39849. }
  39850. }
  39851. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39852. if (parsedGeometry.matricesWeightsExtra) {
  39853. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39854. }
  39855. };
  39856. /**
  39857. * Create a new geometry from persisted data (Using .babylon file format)
  39858. * @param parsedVertexData defines the persisted data
  39859. * @param scene defines the hosting scene
  39860. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39861. * @returns the new geometry object
  39862. */
  39863. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39864. if (scene.getGeometryByID(parsedVertexData.id)) {
  39865. return null; // null since geometry could be something else than a box...
  39866. }
  39867. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39868. if (BABYLON.Tags) {
  39869. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39870. }
  39871. if (parsedVertexData.delayLoadingFile) {
  39872. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39873. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39874. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39875. geometry._delayInfo = [];
  39876. if (parsedVertexData.hasUVs) {
  39877. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39878. }
  39879. if (parsedVertexData.hasUVs2) {
  39880. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39881. }
  39882. if (parsedVertexData.hasUVs3) {
  39883. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39884. }
  39885. if (parsedVertexData.hasUVs4) {
  39886. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39887. }
  39888. if (parsedVertexData.hasUVs5) {
  39889. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39890. }
  39891. if (parsedVertexData.hasUVs6) {
  39892. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39893. }
  39894. if (parsedVertexData.hasColors) {
  39895. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39896. }
  39897. if (parsedVertexData.hasMatricesIndices) {
  39898. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39899. }
  39900. if (parsedVertexData.hasMatricesWeights) {
  39901. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39902. }
  39903. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39904. }
  39905. else {
  39906. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39907. }
  39908. scene.pushGeometry(geometry, true);
  39909. return geometry;
  39910. };
  39911. return Geometry;
  39912. }());
  39913. BABYLON.Geometry = Geometry;
  39914. // Primitives
  39915. /// Abstract class
  39916. /**
  39917. * Abstract class used to provide common services for all typed geometries
  39918. * @hidden
  39919. */
  39920. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39921. __extends(_PrimitiveGeometry, _super);
  39922. /**
  39923. * Creates a new typed geometry
  39924. * @param id defines the unique ID of the geometry
  39925. * @param scene defines the hosting scene
  39926. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39927. * @param mesh defines the hosting mesh (can be null)
  39928. */
  39929. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39930. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39931. if (mesh === void 0) { mesh = null; }
  39932. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39933. _this._canBeRegenerated = _canBeRegenerated;
  39934. _this._beingRegenerated = true;
  39935. _this.regenerate();
  39936. _this._beingRegenerated = false;
  39937. return _this;
  39938. }
  39939. /**
  39940. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39941. * @returns true if the geometry can be regenerated
  39942. */
  39943. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39944. return this._canBeRegenerated;
  39945. };
  39946. /**
  39947. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39948. */
  39949. _PrimitiveGeometry.prototype.regenerate = function () {
  39950. if (!this._canBeRegenerated) {
  39951. return;
  39952. }
  39953. this._beingRegenerated = true;
  39954. this.setAllVerticesData(this._regenerateVertexData(), false);
  39955. this._beingRegenerated = false;
  39956. };
  39957. /**
  39958. * Clone the geometry
  39959. * @param id defines the unique ID of the new geometry
  39960. * @returns the new geometry
  39961. */
  39962. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39963. return _super.prototype.copy.call(this, id);
  39964. };
  39965. // overrides
  39966. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39967. if (!this._beingRegenerated) {
  39968. return;
  39969. }
  39970. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39971. };
  39972. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39973. if (!this._beingRegenerated) {
  39974. return;
  39975. }
  39976. _super.prototype.setVerticesData.call(this, kind, data, false);
  39977. };
  39978. // to override
  39979. /** @hidden */
  39980. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39981. throw new Error("Abstract method");
  39982. };
  39983. _PrimitiveGeometry.prototype.copy = function (id) {
  39984. throw new Error("Must be overriden in sub-classes.");
  39985. };
  39986. _PrimitiveGeometry.prototype.serialize = function () {
  39987. var serializationObject = _super.prototype.serialize.call(this);
  39988. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39989. return serializationObject;
  39990. };
  39991. return _PrimitiveGeometry;
  39992. }(Geometry));
  39993. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39994. /**
  39995. * Creates a ribbon geometry
  39996. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39997. */
  39998. var RibbonGeometry = /** @class */ (function (_super) {
  39999. __extends(RibbonGeometry, _super);
  40000. /**
  40001. * Creates a ribbon geometry
  40002. * @param id defines the unique ID of the geometry
  40003. * @param scene defines the hosting scene
  40004. * @param pathArray defines the array of paths to use
  40005. * @param closeArray defines if the last path and the first path must be joined
  40006. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40007. * @param offset defines the offset between points
  40008. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40009. * @param mesh defines the hosting mesh (can be null)
  40010. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40011. */
  40012. function RibbonGeometry(id, scene,
  40013. /**
  40014. * Defines the array of paths to use
  40015. */
  40016. pathArray,
  40017. /**
  40018. * Defines if the last and first points of each path in your pathArray must be joined
  40019. */
  40020. closeArray,
  40021. /**
  40022. * Defines if the last and first points of each path in your pathArray must be joined
  40023. */
  40024. closePath,
  40025. /**
  40026. * Defines the offset between points
  40027. */
  40028. offset, canBeRegenerated, mesh,
  40029. /**
  40030. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40031. */
  40032. side) {
  40033. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40034. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40035. _this.pathArray = pathArray;
  40036. _this.closeArray = closeArray;
  40037. _this.closePath = closePath;
  40038. _this.offset = offset;
  40039. _this.side = side;
  40040. return _this;
  40041. }
  40042. /** @hidden */
  40043. RibbonGeometry.prototype._regenerateVertexData = function () {
  40044. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40045. };
  40046. RibbonGeometry.prototype.copy = function (id) {
  40047. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40048. };
  40049. return RibbonGeometry;
  40050. }(_PrimitiveGeometry));
  40051. BABYLON.RibbonGeometry = RibbonGeometry;
  40052. /**
  40053. * Creates a box geometry
  40054. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40055. */
  40056. var BoxGeometry = /** @class */ (function (_super) {
  40057. __extends(BoxGeometry, _super);
  40058. /**
  40059. * Creates a box geometry
  40060. * @param id defines the unique ID of the geometry
  40061. * @param scene defines the hosting scene
  40062. * @param size defines the zise of the box (width, height and depth are the same)
  40063. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40064. * @param mesh defines the hosting mesh (can be null)
  40065. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40066. */
  40067. function BoxGeometry(id, scene,
  40068. /**
  40069. * Defines the zise of the box (width, height and depth are the same)
  40070. */
  40071. size, canBeRegenerated, mesh,
  40072. /**
  40073. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40074. */
  40075. side) {
  40076. if (mesh === void 0) { mesh = null; }
  40077. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40078. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40079. _this.size = size;
  40080. _this.side = side;
  40081. return _this;
  40082. }
  40083. /** @hidden */
  40084. BoxGeometry.prototype._regenerateVertexData = function () {
  40085. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40086. };
  40087. BoxGeometry.prototype.copy = function (id) {
  40088. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40089. };
  40090. BoxGeometry.prototype.serialize = function () {
  40091. var serializationObject = _super.prototype.serialize.call(this);
  40092. serializationObject.size = this.size;
  40093. return serializationObject;
  40094. };
  40095. BoxGeometry.Parse = function (parsedBox, scene) {
  40096. if (scene.getGeometryByID(parsedBox.id)) {
  40097. return null; // null since geometry could be something else than a box...
  40098. }
  40099. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40100. if (BABYLON.Tags) {
  40101. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40102. }
  40103. scene.pushGeometry(box, true);
  40104. return box;
  40105. };
  40106. return BoxGeometry;
  40107. }(_PrimitiveGeometry));
  40108. BABYLON.BoxGeometry = BoxGeometry;
  40109. /**
  40110. * Creates a sphere geometry
  40111. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40112. */
  40113. var SphereGeometry = /** @class */ (function (_super) {
  40114. __extends(SphereGeometry, _super);
  40115. /**
  40116. * Create a new sphere geometry
  40117. * @param id defines the unique ID of the geometry
  40118. * @param scene defines the hosting scene
  40119. * @param segments defines the number of segments to use to create the sphere
  40120. * @param diameter defines the diameter of the sphere
  40121. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40122. * @param mesh defines the hosting mesh (can be null)
  40123. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40124. */
  40125. function SphereGeometry(id, scene,
  40126. /**
  40127. * Defines the number of segments to use to create the sphere
  40128. */
  40129. segments,
  40130. /**
  40131. * Defines the diameter of the sphere
  40132. */
  40133. diameter, canBeRegenerated, mesh,
  40134. /**
  40135. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40136. */
  40137. side) {
  40138. if (mesh === void 0) { mesh = null; }
  40139. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40140. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40141. _this.segments = segments;
  40142. _this.diameter = diameter;
  40143. _this.side = side;
  40144. return _this;
  40145. }
  40146. /** @hidden */
  40147. SphereGeometry.prototype._regenerateVertexData = function () {
  40148. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40149. };
  40150. SphereGeometry.prototype.copy = function (id) {
  40151. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40152. };
  40153. SphereGeometry.prototype.serialize = function () {
  40154. var serializationObject = _super.prototype.serialize.call(this);
  40155. serializationObject.segments = this.segments;
  40156. serializationObject.diameter = this.diameter;
  40157. return serializationObject;
  40158. };
  40159. SphereGeometry.Parse = function (parsedSphere, scene) {
  40160. if (scene.getGeometryByID(parsedSphere.id)) {
  40161. return null; // null since geometry could be something else than a sphere...
  40162. }
  40163. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40164. if (BABYLON.Tags) {
  40165. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40166. }
  40167. scene.pushGeometry(sphere, true);
  40168. return sphere;
  40169. };
  40170. return SphereGeometry;
  40171. }(_PrimitiveGeometry));
  40172. BABYLON.SphereGeometry = SphereGeometry;
  40173. /**
  40174. * Creates a disc geometry
  40175. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40176. */
  40177. var DiscGeometry = /** @class */ (function (_super) {
  40178. __extends(DiscGeometry, _super);
  40179. /**
  40180. * Creates a new disc geometry
  40181. * @param id defines the unique ID of the geometry
  40182. * @param scene defines the hosting scene
  40183. * @param radius defines the radius of the disc
  40184. * @param tessellation defines the tesselation factor to apply to the disc
  40185. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40186. * @param mesh defines the hosting mesh (can be null)
  40187. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40188. */
  40189. function DiscGeometry(id, scene,
  40190. /**
  40191. * Defines the radius of the disc
  40192. */
  40193. radius,
  40194. /**
  40195. * Defines the tesselation factor to apply to the disc
  40196. */
  40197. tessellation, canBeRegenerated, mesh,
  40198. /**
  40199. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40200. */
  40201. side) {
  40202. if (mesh === void 0) { mesh = null; }
  40203. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40204. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40205. _this.radius = radius;
  40206. _this.tessellation = tessellation;
  40207. _this.side = side;
  40208. return _this;
  40209. }
  40210. /** @hidden */
  40211. DiscGeometry.prototype._regenerateVertexData = function () {
  40212. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40213. };
  40214. DiscGeometry.prototype.copy = function (id) {
  40215. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40216. };
  40217. return DiscGeometry;
  40218. }(_PrimitiveGeometry));
  40219. BABYLON.DiscGeometry = DiscGeometry;
  40220. /**
  40221. * Creates a new cylinder geometry
  40222. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40223. */
  40224. var CylinderGeometry = /** @class */ (function (_super) {
  40225. __extends(CylinderGeometry, _super);
  40226. /**
  40227. * Creates a new cylinder geometry
  40228. * @param id defines the unique ID of the geometry
  40229. * @param scene defines the hosting scene
  40230. * @param height defines the height of the cylinder
  40231. * @param diameterTop defines the diameter of the cylinder's top cap
  40232. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40233. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40234. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40235. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40236. * @param mesh defines the hosting mesh (can be null)
  40237. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40238. */
  40239. function CylinderGeometry(id, scene,
  40240. /**
  40241. * Defines the height of the cylinder
  40242. */
  40243. height,
  40244. /**
  40245. * Defines the diameter of the cylinder's top cap
  40246. */
  40247. diameterTop,
  40248. /**
  40249. * Defines the diameter of the cylinder's bottom cap
  40250. */
  40251. diameterBottom,
  40252. /**
  40253. * Defines the tessellation factor to apply to the cylinder
  40254. */
  40255. tessellation,
  40256. /**
  40257. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40258. */
  40259. subdivisions, canBeRegenerated, mesh,
  40260. /**
  40261. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40262. */
  40263. side) {
  40264. if (subdivisions === void 0) { subdivisions = 1; }
  40265. if (mesh === void 0) { mesh = null; }
  40266. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40267. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40268. _this.height = height;
  40269. _this.diameterTop = diameterTop;
  40270. _this.diameterBottom = diameterBottom;
  40271. _this.tessellation = tessellation;
  40272. _this.subdivisions = subdivisions;
  40273. _this.side = side;
  40274. return _this;
  40275. }
  40276. /** @hidden */
  40277. CylinderGeometry.prototype._regenerateVertexData = function () {
  40278. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40279. };
  40280. CylinderGeometry.prototype.copy = function (id) {
  40281. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40282. };
  40283. CylinderGeometry.prototype.serialize = function () {
  40284. var serializationObject = _super.prototype.serialize.call(this);
  40285. serializationObject.height = this.height;
  40286. serializationObject.diameterTop = this.diameterTop;
  40287. serializationObject.diameterBottom = this.diameterBottom;
  40288. serializationObject.tessellation = this.tessellation;
  40289. return serializationObject;
  40290. };
  40291. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40292. if (scene.getGeometryByID(parsedCylinder.id)) {
  40293. return null; // null since geometry could be something else than a cylinder...
  40294. }
  40295. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40296. if (BABYLON.Tags) {
  40297. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40298. }
  40299. scene.pushGeometry(cylinder, true);
  40300. return cylinder;
  40301. };
  40302. return CylinderGeometry;
  40303. }(_PrimitiveGeometry));
  40304. BABYLON.CylinderGeometry = CylinderGeometry;
  40305. /**
  40306. * Creates a new torus geometry
  40307. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40308. */
  40309. var TorusGeometry = /** @class */ (function (_super) {
  40310. __extends(TorusGeometry, _super);
  40311. /**
  40312. * Creates a new torus geometry
  40313. * @param id defines the unique ID of the geometry
  40314. * @param scene defines the hosting scene
  40315. * @param diameter defines the diameter of the torus
  40316. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40317. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40318. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40319. * @param mesh defines the hosting mesh (can be null)
  40320. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40321. */
  40322. function TorusGeometry(id, scene,
  40323. /**
  40324. * Defines the diameter of the torus
  40325. */
  40326. diameter,
  40327. /**
  40328. * Defines the thickness of the torus (ie. internal diameter)
  40329. */
  40330. thickness,
  40331. /**
  40332. * Defines the tesselation factor to apply to the torus
  40333. */
  40334. tessellation, canBeRegenerated, mesh,
  40335. /**
  40336. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40337. */
  40338. side) {
  40339. if (mesh === void 0) { mesh = null; }
  40340. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40341. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40342. _this.diameter = diameter;
  40343. _this.thickness = thickness;
  40344. _this.tessellation = tessellation;
  40345. _this.side = side;
  40346. return _this;
  40347. }
  40348. /** @hidden */
  40349. TorusGeometry.prototype._regenerateVertexData = function () {
  40350. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40351. };
  40352. TorusGeometry.prototype.copy = function (id) {
  40353. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40354. };
  40355. TorusGeometry.prototype.serialize = function () {
  40356. var serializationObject = _super.prototype.serialize.call(this);
  40357. serializationObject.diameter = this.diameter;
  40358. serializationObject.thickness = this.thickness;
  40359. serializationObject.tessellation = this.tessellation;
  40360. return serializationObject;
  40361. };
  40362. TorusGeometry.Parse = function (parsedTorus, scene) {
  40363. if (scene.getGeometryByID(parsedTorus.id)) {
  40364. return null; // null since geometry could be something else than a torus...
  40365. }
  40366. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40367. if (BABYLON.Tags) {
  40368. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40369. }
  40370. scene.pushGeometry(torus, true);
  40371. return torus;
  40372. };
  40373. return TorusGeometry;
  40374. }(_PrimitiveGeometry));
  40375. BABYLON.TorusGeometry = TorusGeometry;
  40376. /**
  40377. * Creates a new ground geometry
  40378. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40379. */
  40380. var GroundGeometry = /** @class */ (function (_super) {
  40381. __extends(GroundGeometry, _super);
  40382. /**
  40383. * Creates a new ground geometry
  40384. * @param id defines the unique ID of the geometry
  40385. * @param scene defines the hosting scene
  40386. * @param width defines the width of the ground
  40387. * @param height defines the height of the ground
  40388. * @param subdivisions defines the subdivisions to apply to the ground
  40389. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40390. * @param mesh defines the hosting mesh (can be null)
  40391. */
  40392. function GroundGeometry(id, scene,
  40393. /**
  40394. * Defines the width of the ground
  40395. */
  40396. width,
  40397. /**
  40398. * Defines the height of the ground
  40399. */
  40400. height,
  40401. /**
  40402. * Defines the subdivisions to apply to the ground
  40403. */
  40404. subdivisions, canBeRegenerated, mesh) {
  40405. if (mesh === void 0) { mesh = null; }
  40406. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40407. _this.width = width;
  40408. _this.height = height;
  40409. _this.subdivisions = subdivisions;
  40410. return _this;
  40411. }
  40412. /** @hidden */
  40413. GroundGeometry.prototype._regenerateVertexData = function () {
  40414. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40415. };
  40416. GroundGeometry.prototype.copy = function (id) {
  40417. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40418. };
  40419. GroundGeometry.prototype.serialize = function () {
  40420. var serializationObject = _super.prototype.serialize.call(this);
  40421. serializationObject.width = this.width;
  40422. serializationObject.height = this.height;
  40423. serializationObject.subdivisions = this.subdivisions;
  40424. return serializationObject;
  40425. };
  40426. GroundGeometry.Parse = function (parsedGround, scene) {
  40427. if (scene.getGeometryByID(parsedGround.id)) {
  40428. return null; // null since geometry could be something else than a ground...
  40429. }
  40430. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40431. if (BABYLON.Tags) {
  40432. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40433. }
  40434. scene.pushGeometry(ground, true);
  40435. return ground;
  40436. };
  40437. return GroundGeometry;
  40438. }(_PrimitiveGeometry));
  40439. BABYLON.GroundGeometry = GroundGeometry;
  40440. /**
  40441. * Creates a tiled ground geometry
  40442. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40443. */
  40444. var TiledGroundGeometry = /** @class */ (function (_super) {
  40445. __extends(TiledGroundGeometry, _super);
  40446. /**
  40447. * Creates a tiled ground geometry
  40448. * @param id defines the unique ID of the geometry
  40449. * @param scene defines the hosting scene
  40450. * @param xmin defines the minimum value on X axis
  40451. * @param zmin defines the minimum value on Z axis
  40452. * @param xmax defines the maximum value on X axis
  40453. * @param zmax defines the maximum value on Z axis
  40454. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40455. * @param precision defines the precision to use when computing the tiles
  40456. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40457. * @param mesh defines the hosting mesh (can be null)
  40458. */
  40459. function TiledGroundGeometry(id, scene,
  40460. /**
  40461. * Defines the minimum value on X axis
  40462. */
  40463. xmin,
  40464. /**
  40465. * Defines the minimum value on Z axis
  40466. */
  40467. zmin,
  40468. /**
  40469. * Defines the maximum value on X axis
  40470. */
  40471. xmax,
  40472. /**
  40473. * Defines the maximum value on Z axis
  40474. */
  40475. zmax,
  40476. /**
  40477. * Defines the subdivisions to apply to the ground
  40478. */
  40479. subdivisions,
  40480. /**
  40481. * Defines the precision to use when computing the tiles
  40482. */
  40483. precision, canBeRegenerated, mesh) {
  40484. if (mesh === void 0) { mesh = null; }
  40485. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40486. _this.xmin = xmin;
  40487. _this.zmin = zmin;
  40488. _this.xmax = xmax;
  40489. _this.zmax = zmax;
  40490. _this.subdivisions = subdivisions;
  40491. _this.precision = precision;
  40492. return _this;
  40493. }
  40494. /** @hidden */
  40495. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40496. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40497. };
  40498. TiledGroundGeometry.prototype.copy = function (id) {
  40499. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40500. };
  40501. return TiledGroundGeometry;
  40502. }(_PrimitiveGeometry));
  40503. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40504. /**
  40505. * Creates a plane geometry
  40506. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40507. */
  40508. var PlaneGeometry = /** @class */ (function (_super) {
  40509. __extends(PlaneGeometry, _super);
  40510. /**
  40511. * Creates a plane geometry
  40512. * @param id defines the unique ID of the geometry
  40513. * @param scene defines the hosting scene
  40514. * @param size defines the size of the plane (width === height)
  40515. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40516. * @param mesh defines the hosting mesh (can be null)
  40517. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40518. */
  40519. function PlaneGeometry(id, scene,
  40520. /**
  40521. * Defines the size of the plane (width === height)
  40522. */
  40523. size, canBeRegenerated, mesh,
  40524. /**
  40525. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40526. */
  40527. side) {
  40528. if (mesh === void 0) { mesh = null; }
  40529. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40530. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40531. _this.size = size;
  40532. _this.side = side;
  40533. return _this;
  40534. }
  40535. /** @hidden */
  40536. PlaneGeometry.prototype._regenerateVertexData = function () {
  40537. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40538. };
  40539. PlaneGeometry.prototype.copy = function (id) {
  40540. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40541. };
  40542. PlaneGeometry.prototype.serialize = function () {
  40543. var serializationObject = _super.prototype.serialize.call(this);
  40544. serializationObject.size = this.size;
  40545. return serializationObject;
  40546. };
  40547. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40548. if (scene.getGeometryByID(parsedPlane.id)) {
  40549. return null; // null since geometry could be something else than a ground...
  40550. }
  40551. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40552. if (BABYLON.Tags) {
  40553. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40554. }
  40555. scene.pushGeometry(plane, true);
  40556. return plane;
  40557. };
  40558. return PlaneGeometry;
  40559. }(_PrimitiveGeometry));
  40560. BABYLON.PlaneGeometry = PlaneGeometry;
  40561. /**
  40562. * Creates a torus knot geometry
  40563. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40564. */
  40565. var TorusKnotGeometry = /** @class */ (function (_super) {
  40566. __extends(TorusKnotGeometry, _super);
  40567. /**
  40568. * Creates a torus knot geometry
  40569. * @param id defines the unique ID of the geometry
  40570. * @param scene defines the hosting scene
  40571. * @param radius defines the radius of the torus knot
  40572. * @param tube defines the thickness of the torus knot tube
  40573. * @param radialSegments defines the number of radial segments
  40574. * @param tubularSegments defines the number of tubular segments
  40575. * @param p defines the first number of windings
  40576. * @param q defines the second number of windings
  40577. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40578. * @param mesh defines the hosting mesh (can be null)
  40579. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40580. */
  40581. function TorusKnotGeometry(id, scene,
  40582. /**
  40583. * Defines the radius of the torus knot
  40584. */
  40585. radius,
  40586. /**
  40587. * Defines the thickness of the torus knot tube
  40588. */
  40589. tube,
  40590. /**
  40591. * Defines the number of radial segments
  40592. */
  40593. radialSegments,
  40594. /**
  40595. * Defines the number of tubular segments
  40596. */
  40597. tubularSegments,
  40598. /**
  40599. * Defines the first number of windings
  40600. */
  40601. p,
  40602. /**
  40603. * Defines the second number of windings
  40604. */
  40605. q, canBeRegenerated, mesh,
  40606. /**
  40607. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40608. */
  40609. side) {
  40610. if (mesh === void 0) { mesh = null; }
  40611. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40612. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40613. _this.radius = radius;
  40614. _this.tube = tube;
  40615. _this.radialSegments = radialSegments;
  40616. _this.tubularSegments = tubularSegments;
  40617. _this.p = p;
  40618. _this.q = q;
  40619. _this.side = side;
  40620. return _this;
  40621. }
  40622. /** @hidden */
  40623. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40624. 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 });
  40625. };
  40626. TorusKnotGeometry.prototype.copy = function (id) {
  40627. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40628. };
  40629. TorusKnotGeometry.prototype.serialize = function () {
  40630. var serializationObject = _super.prototype.serialize.call(this);
  40631. serializationObject.radius = this.radius;
  40632. serializationObject.tube = this.tube;
  40633. serializationObject.radialSegments = this.radialSegments;
  40634. serializationObject.tubularSegments = this.tubularSegments;
  40635. serializationObject.p = this.p;
  40636. serializationObject.q = this.q;
  40637. return serializationObject;
  40638. };
  40639. ;
  40640. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40641. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40642. return null; // null since geometry could be something else than a ground...
  40643. }
  40644. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40645. if (BABYLON.Tags) {
  40646. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40647. }
  40648. scene.pushGeometry(torusKnot, true);
  40649. return torusKnot;
  40650. };
  40651. return TorusKnotGeometry;
  40652. }(_PrimitiveGeometry));
  40653. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40654. //}
  40655. })(BABYLON || (BABYLON = {}));
  40656. //# sourceMappingURL=babylon.geometry.js.map
  40657. var BABYLON;
  40658. (function (BABYLON) {
  40659. /**
  40660. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40661. */
  40662. var PerformanceMonitor = /** @class */ (function () {
  40663. /**
  40664. * constructor
  40665. * @param frameSampleSize The number of samples required to saturate the sliding window
  40666. */
  40667. function PerformanceMonitor(frameSampleSize) {
  40668. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40669. this._enabled = true;
  40670. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40671. }
  40672. /**
  40673. * Samples current frame
  40674. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40675. */
  40676. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40677. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40678. if (!this._enabled)
  40679. return;
  40680. if (this._lastFrameTimeMs != null) {
  40681. var dt = timeMs - this._lastFrameTimeMs;
  40682. this._rollingFrameTime.add(dt);
  40683. }
  40684. this._lastFrameTimeMs = timeMs;
  40685. };
  40686. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40687. /**
  40688. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40689. * @return Average frame time in milliseconds
  40690. */
  40691. get: function () {
  40692. return this._rollingFrameTime.average;
  40693. },
  40694. enumerable: true,
  40695. configurable: true
  40696. });
  40697. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40698. /**
  40699. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40700. * @return Frame time variance in milliseconds squared
  40701. */
  40702. get: function () {
  40703. return this._rollingFrameTime.variance;
  40704. },
  40705. enumerable: true,
  40706. configurable: true
  40707. });
  40708. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40709. /**
  40710. * Returns the frame time of the most recent frame
  40711. * @return Frame time in milliseconds
  40712. */
  40713. get: function () {
  40714. return this._rollingFrameTime.history(0);
  40715. },
  40716. enumerable: true,
  40717. configurable: true
  40718. });
  40719. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40720. /**
  40721. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40722. * @return Framerate in frames per second
  40723. */
  40724. get: function () {
  40725. return 1000.0 / this._rollingFrameTime.average;
  40726. },
  40727. enumerable: true,
  40728. configurable: true
  40729. });
  40730. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40731. /**
  40732. * Returns the average framerate in frames per second using the most recent frame time
  40733. * @return Framerate in frames per second
  40734. */
  40735. get: function () {
  40736. var history = this._rollingFrameTime.history(0);
  40737. if (history === 0) {
  40738. return 0;
  40739. }
  40740. return 1000.0 / history;
  40741. },
  40742. enumerable: true,
  40743. configurable: true
  40744. });
  40745. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40746. /**
  40747. * Returns true if enough samples have been taken to completely fill the sliding window
  40748. * @return true if saturated
  40749. */
  40750. get: function () {
  40751. return this._rollingFrameTime.isSaturated();
  40752. },
  40753. enumerable: true,
  40754. configurable: true
  40755. });
  40756. /**
  40757. * Enables contributions to the sliding window sample set
  40758. */
  40759. PerformanceMonitor.prototype.enable = function () {
  40760. this._enabled = true;
  40761. };
  40762. /**
  40763. * Disables contributions to the sliding window sample set
  40764. * Samples will not be interpolated over the disabled period
  40765. */
  40766. PerformanceMonitor.prototype.disable = function () {
  40767. this._enabled = false;
  40768. //clear last sample to avoid interpolating over the disabled period when next enabled
  40769. this._lastFrameTimeMs = null;
  40770. };
  40771. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40772. /**
  40773. * Returns true if sampling is enabled
  40774. * @return true if enabled
  40775. */
  40776. get: function () {
  40777. return this._enabled;
  40778. },
  40779. enumerable: true,
  40780. configurable: true
  40781. });
  40782. /**
  40783. * Resets performance monitor
  40784. */
  40785. PerformanceMonitor.prototype.reset = function () {
  40786. //clear last sample to avoid interpolating over the disabled period when next enabled
  40787. this._lastFrameTimeMs = null;
  40788. //wipe record
  40789. this._rollingFrameTime.reset();
  40790. };
  40791. return PerformanceMonitor;
  40792. }());
  40793. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40794. /**
  40795. * RollingAverage
  40796. *
  40797. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40798. */
  40799. var RollingAverage = /** @class */ (function () {
  40800. /**
  40801. * constructor
  40802. * @param length The number of samples required to saturate the sliding window
  40803. */
  40804. function RollingAverage(length) {
  40805. this._samples = new Array(length);
  40806. this.reset();
  40807. }
  40808. /**
  40809. * Adds a sample to the sample set
  40810. * @param v The sample value
  40811. */
  40812. RollingAverage.prototype.add = function (v) {
  40813. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40814. var delta;
  40815. //we need to check if we've already wrapped round
  40816. if (this.isSaturated()) {
  40817. //remove bottom of stack from mean
  40818. var bottomValue = this._samples[this._pos];
  40819. delta = bottomValue - this.average;
  40820. this.average -= delta / (this._sampleCount - 1);
  40821. this._m2 -= delta * (bottomValue - this.average);
  40822. }
  40823. else {
  40824. this._sampleCount++;
  40825. }
  40826. //add new value to mean
  40827. delta = v - this.average;
  40828. this.average += delta / (this._sampleCount);
  40829. this._m2 += delta * (v - this.average);
  40830. //set the new variance
  40831. this.variance = this._m2 / (this._sampleCount - 1);
  40832. this._samples[this._pos] = v;
  40833. this._pos++;
  40834. this._pos %= this._samples.length; //positive wrap around
  40835. };
  40836. /**
  40837. * Returns previously added values or null if outside of history or outside the sliding window domain
  40838. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40839. * @return Value previously recorded with add() or null if outside of range
  40840. */
  40841. RollingAverage.prototype.history = function (i) {
  40842. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40843. return 0;
  40844. }
  40845. var i0 = this._wrapPosition(this._pos - 1.0);
  40846. return this._samples[this._wrapPosition(i0 - i)];
  40847. };
  40848. /**
  40849. * Returns true if enough samples have been taken to completely fill the sliding window
  40850. * @return true if sample-set saturated
  40851. */
  40852. RollingAverage.prototype.isSaturated = function () {
  40853. return this._sampleCount >= this._samples.length;
  40854. };
  40855. /**
  40856. * Resets the rolling average (equivalent to 0 samples taken so far)
  40857. */
  40858. RollingAverage.prototype.reset = function () {
  40859. this.average = 0;
  40860. this.variance = 0;
  40861. this._sampleCount = 0;
  40862. this._pos = 0;
  40863. this._m2 = 0;
  40864. };
  40865. /**
  40866. * Wraps a value around the sample range boundaries
  40867. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40868. * @return Wrapped position in sample range
  40869. */
  40870. RollingAverage.prototype._wrapPosition = function (i) {
  40871. var max = this._samples.length;
  40872. return ((i % max) + max) % max;
  40873. };
  40874. return RollingAverage;
  40875. }());
  40876. BABYLON.RollingAverage = RollingAverage;
  40877. })(BABYLON || (BABYLON = {}));
  40878. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40879. var BABYLON;
  40880. (function (BABYLON) {
  40881. /**
  40882. * "Static Class" containing the most commonly used helper while dealing with material for
  40883. * rendering purpose.
  40884. *
  40885. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40886. *
  40887. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40888. */
  40889. var MaterialHelper = /** @class */ (function () {
  40890. function MaterialHelper() {
  40891. }
  40892. /**
  40893. * Bind the current view position to an effect.
  40894. * @param effect The effect to be bound
  40895. * @param scene The scene the eyes position is used from
  40896. */
  40897. MaterialHelper.BindEyePosition = function (effect, scene) {
  40898. if (scene._forcedViewPosition) {
  40899. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40900. return;
  40901. }
  40902. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40903. };
  40904. /**
  40905. * Helps preparing the defines values about the UVs in used in the effect.
  40906. * UVs are shared as much as we can accross chanels in the shaders.
  40907. * @param texture The texture we are preparing the UVs for
  40908. * @param defines The defines to update
  40909. * @param key The chanel key "diffuse", "specular"... used in the shader
  40910. */
  40911. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40912. defines._needUVs = true;
  40913. defines[key] = true;
  40914. if (texture.getTextureMatrix().isIdentity(true)) {
  40915. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40916. if (texture.coordinatesIndex === 0) {
  40917. defines["MAINUV1"] = true;
  40918. }
  40919. else {
  40920. defines["MAINUV2"] = true;
  40921. }
  40922. }
  40923. else {
  40924. defines[key + "DIRECTUV"] = 0;
  40925. }
  40926. };
  40927. /**
  40928. * Binds a texture matrix value to its corrsponding uniform
  40929. * @param texture The texture to bind the matrix for
  40930. * @param uniformBuffer The uniform buffer receivin the data
  40931. * @param key The chanel key "diffuse", "specular"... used in the shader
  40932. */
  40933. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40934. var matrix = texture.getTextureMatrix();
  40935. if (!matrix.isIdentity(true)) {
  40936. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40937. }
  40938. };
  40939. /**
  40940. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40941. * @param mesh defines the current mesh
  40942. * @param scene defines the current scene
  40943. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40944. * @param pointsCloud defines if point cloud rendering has to be turned on
  40945. * @param fogEnabled defines if fog has to be turned on
  40946. * @param alphaTest defines if alpha testing has to be turned on
  40947. * @param defines defines the current list of defines
  40948. */
  40949. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40950. if (defines._areMiscDirty) {
  40951. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40952. defines["POINTSIZE"] = pointsCloud;
  40953. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40954. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40955. defines["ALPHATEST"] = alphaTest;
  40956. }
  40957. };
  40958. /**
  40959. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40960. * @param scene defines the current scene
  40961. * @param engine defines the current engine
  40962. * @param defines specifies the list of active defines
  40963. * @param useInstances defines if instances have to be turned on
  40964. * @param useClipPlane defines if clip plane have to be turned on
  40965. */
  40966. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40967. if (useClipPlane === void 0) { useClipPlane = null; }
  40968. var changed = false;
  40969. if (useClipPlane == null) {
  40970. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40971. }
  40972. if (defines["CLIPPLANE"] !== useClipPlane) {
  40973. defines["CLIPPLANE"] = useClipPlane;
  40974. changed = true;
  40975. }
  40976. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40977. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40978. changed = true;
  40979. }
  40980. if (defines["INSTANCES"] !== useInstances) {
  40981. defines["INSTANCES"] = useInstances;
  40982. changed = true;
  40983. }
  40984. if (changed) {
  40985. defines.markAsUnprocessed();
  40986. }
  40987. };
  40988. /**
  40989. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40990. * @param mesh The mesh containing the geometry data we will draw
  40991. * @param defines The defines to update
  40992. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40993. * @param useBones Precise whether bones should be used or not (override mesh info)
  40994. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40995. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40996. * @returns false if defines are considered not dirty and have not been checked
  40997. */
  40998. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40999. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41000. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41001. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41002. return false;
  41003. }
  41004. defines._normals = defines._needNormals;
  41005. defines._uvs = defines._needUVs;
  41006. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41007. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41008. defines["TANGENT"] = true;
  41009. }
  41010. if (defines._needUVs) {
  41011. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41012. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41013. }
  41014. else {
  41015. defines["UV1"] = false;
  41016. defines["UV2"] = false;
  41017. }
  41018. if (useVertexColor) {
  41019. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41020. defines["VERTEXCOLOR"] = hasVertexColors;
  41021. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41022. }
  41023. if (useBones) {
  41024. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41025. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41026. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41027. }
  41028. else {
  41029. defines["NUM_BONE_INFLUENCERS"] = 0;
  41030. defines["BonesPerMesh"] = 0;
  41031. }
  41032. }
  41033. if (useMorphTargets) {
  41034. var manager = mesh.morphTargetManager;
  41035. if (manager) {
  41036. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41037. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41038. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41039. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41040. }
  41041. else {
  41042. defines["MORPHTARGETS_TANGENT"] = false;
  41043. defines["MORPHTARGETS_NORMAL"] = false;
  41044. defines["MORPHTARGETS"] = false;
  41045. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41046. }
  41047. }
  41048. return true;
  41049. };
  41050. /**
  41051. * Prepares the defines related to the light information passed in parameter
  41052. * @param scene The scene we are intending to draw
  41053. * @param mesh The mesh the effect is compiling for
  41054. * @param defines The defines to update
  41055. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41056. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41057. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41058. * @returns true if normals will be required for the rest of the effect
  41059. */
  41060. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41061. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41062. if (disableLighting === void 0) { disableLighting = false; }
  41063. if (!defines._areLightsDirty) {
  41064. return defines._needNormals;
  41065. }
  41066. var lightIndex = 0;
  41067. var needNormals = false;
  41068. var needRebuild = false;
  41069. var lightmapMode = false;
  41070. var shadowEnabled = false;
  41071. var specularEnabled = false;
  41072. if (scene.lightsEnabled && !disableLighting) {
  41073. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41074. var light = _a[_i];
  41075. needNormals = true;
  41076. if (defines["LIGHT" + lightIndex] === undefined) {
  41077. needRebuild = true;
  41078. }
  41079. defines["LIGHT" + lightIndex] = true;
  41080. defines["SPOTLIGHT" + lightIndex] = false;
  41081. defines["HEMILIGHT" + lightIndex] = false;
  41082. defines["POINTLIGHT" + lightIndex] = false;
  41083. defines["DIRLIGHT" + lightIndex] = false;
  41084. light.prepareLightSpecificDefines(defines, lightIndex);
  41085. // FallOff.
  41086. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41087. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41088. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41089. switch (light.falloffType) {
  41090. case BABYLON.Light.FALLOFF_GLTF:
  41091. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41092. break;
  41093. case BABYLON.Light.FALLOFF_PHYSICAL:
  41094. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41095. break;
  41096. case BABYLON.Light.FALLOFF_STANDARD:
  41097. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41098. break;
  41099. }
  41100. // Specular
  41101. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41102. specularEnabled = true;
  41103. }
  41104. // Shadows
  41105. defines["SHADOW" + lightIndex] = false;
  41106. defines["SHADOWPCF" + lightIndex] = false;
  41107. defines["SHADOWPCSS" + lightIndex] = false;
  41108. defines["SHADOWPOISSON" + lightIndex] = false;
  41109. defines["SHADOWESM" + lightIndex] = false;
  41110. defines["SHADOWCUBE" + lightIndex] = false;
  41111. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41112. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41113. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41114. var shadowGenerator = light.getShadowGenerator();
  41115. if (shadowGenerator) {
  41116. var shadowMap = shadowGenerator.getShadowMap();
  41117. if (shadowMap) {
  41118. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41119. shadowEnabled = true;
  41120. shadowGenerator.prepareDefines(defines, lightIndex);
  41121. }
  41122. }
  41123. }
  41124. }
  41125. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41126. lightmapMode = true;
  41127. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41128. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41129. }
  41130. else {
  41131. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41132. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41133. }
  41134. lightIndex++;
  41135. if (lightIndex === maxSimultaneousLights)
  41136. break;
  41137. }
  41138. }
  41139. defines["SPECULARTERM"] = specularEnabled;
  41140. defines["SHADOWS"] = shadowEnabled;
  41141. // Resetting all other lights if any
  41142. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41143. if (defines["LIGHT" + index] !== undefined) {
  41144. defines["LIGHT" + index] = false;
  41145. defines["HEMILIGHT" + lightIndex] = false;
  41146. defines["POINTLIGHT" + lightIndex] = false;
  41147. defines["DIRLIGHT" + lightIndex] = false;
  41148. defines["SPOTLIGHT" + lightIndex] = false;
  41149. defines["SHADOW" + lightIndex] = false;
  41150. }
  41151. }
  41152. var caps = scene.getEngine().getCaps();
  41153. if (defines["SHADOWFLOAT"] === undefined) {
  41154. needRebuild = true;
  41155. }
  41156. defines["SHADOWFLOAT"] = shadowEnabled &&
  41157. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41158. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41159. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41160. if (needRebuild) {
  41161. defines.rebuild();
  41162. }
  41163. return needNormals;
  41164. };
  41165. /**
  41166. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41167. * that won t be acctive due to defines being turned off.
  41168. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41169. * @param samplersList The samplers list
  41170. * @param defines The defines helping in the list generation
  41171. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41172. */
  41173. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41174. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41175. var uniformsList;
  41176. var uniformBuffersList = null;
  41177. if (uniformsListOrOptions.uniformsNames) {
  41178. var options = uniformsListOrOptions;
  41179. uniformsList = options.uniformsNames;
  41180. uniformBuffersList = options.uniformBuffersNames;
  41181. samplersList = options.samplers;
  41182. defines = options.defines;
  41183. maxSimultaneousLights = options.maxSimultaneousLights;
  41184. }
  41185. else {
  41186. uniformsList = uniformsListOrOptions;
  41187. if (!samplersList) {
  41188. samplersList = [];
  41189. }
  41190. }
  41191. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41192. if (!defines["LIGHT" + lightIndex]) {
  41193. break;
  41194. }
  41195. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41196. if (uniformBuffersList) {
  41197. uniformBuffersList.push("Light" + lightIndex);
  41198. }
  41199. samplersList.push("shadowSampler" + lightIndex);
  41200. samplersList.push("depthSampler" + lightIndex);
  41201. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41202. samplersList.push("projectionLightSampler" + lightIndex);
  41203. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41204. }
  41205. }
  41206. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41207. uniformsList.push("morphTargetInfluences");
  41208. }
  41209. };
  41210. /**
  41211. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41212. * @param defines The defines to update while falling back
  41213. * @param fallbacks The authorized effect fallbacks
  41214. * @param maxSimultaneousLights The maximum number of lights allowed
  41215. * @param rank the current rank of the Effect
  41216. * @returns The newly affected rank
  41217. */
  41218. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41219. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41220. if (rank === void 0) { rank = 0; }
  41221. var lightFallbackRank = 0;
  41222. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41223. if (!defines["LIGHT" + lightIndex]) {
  41224. break;
  41225. }
  41226. if (lightIndex > 0) {
  41227. lightFallbackRank = rank + lightIndex;
  41228. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41229. }
  41230. if (!defines["SHADOWS"]) {
  41231. if (defines["SHADOW" + lightIndex]) {
  41232. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41233. }
  41234. if (defines["SHADOWPCF" + lightIndex]) {
  41235. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41236. }
  41237. if (defines["SHADOWPCSS" + lightIndex]) {
  41238. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41239. }
  41240. if (defines["SHADOWPOISSON" + lightIndex]) {
  41241. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41242. }
  41243. if (defines["SHADOWESM" + lightIndex]) {
  41244. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41245. }
  41246. }
  41247. }
  41248. return lightFallbackRank++;
  41249. };
  41250. /**
  41251. * Prepares the list of attributes required for morph targets according to the effect defines.
  41252. * @param attribs The current list of supported attribs
  41253. * @param mesh The mesh to prepare the morph targets attributes for
  41254. * @param defines The current Defines of the effect
  41255. */
  41256. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41257. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41258. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41259. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41260. var manager = mesh.morphTargetManager;
  41261. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41262. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41263. for (var index = 0; index < influencers; index++) {
  41264. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41265. if (normal) {
  41266. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41267. }
  41268. if (tangent) {
  41269. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41270. }
  41271. if (attribs.length > maxAttributesCount) {
  41272. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41273. }
  41274. }
  41275. }
  41276. };
  41277. /**
  41278. * Prepares the list of attributes required for bones according to the effect defines.
  41279. * @param attribs The current list of supported attribs
  41280. * @param mesh The mesh to prepare the bones attributes for
  41281. * @param defines The current Defines of the effect
  41282. * @param fallbacks The current efffect fallback strategy
  41283. */
  41284. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41285. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41286. fallbacks.addCPUSkinningFallback(0, mesh);
  41287. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41288. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41289. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41290. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41291. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41292. }
  41293. }
  41294. };
  41295. /**
  41296. * Prepares the list of attributes required for instances according to the effect defines.
  41297. * @param attribs The current list of supported attribs
  41298. * @param defines The current Defines of the effect
  41299. */
  41300. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41301. if (defines["INSTANCES"]) {
  41302. attribs.push("world0");
  41303. attribs.push("world1");
  41304. attribs.push("world2");
  41305. attribs.push("world3");
  41306. }
  41307. };
  41308. /**
  41309. * Binds the light shadow information to the effect for the given mesh.
  41310. * @param light The light containing the generator
  41311. * @param scene The scene the lights belongs to
  41312. * @param mesh The mesh we are binding the information to render
  41313. * @param lightIndex The light index in the effect used to render the mesh
  41314. * @param effect The effect we are binding the data to
  41315. */
  41316. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41317. if (light.shadowEnabled && mesh.receiveShadows) {
  41318. var shadowGenerator = light.getShadowGenerator();
  41319. if (shadowGenerator) {
  41320. shadowGenerator.bindShadowLight(lightIndex, effect);
  41321. }
  41322. }
  41323. };
  41324. /**
  41325. * Binds the light information to the effect.
  41326. * @param light The light containing the generator
  41327. * @param effect The effect we are binding the data to
  41328. * @param lightIndex The light index in the effect used to render
  41329. */
  41330. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41331. light.transferToEffect(effect, lightIndex + "");
  41332. };
  41333. /**
  41334. * Binds the lights information from the scene to the effect for the given mesh.
  41335. * @param scene The scene the lights belongs to
  41336. * @param mesh The mesh we are binding the information to render
  41337. * @param effect The effect we are binding the data to
  41338. * @param defines The generated defines for the effect
  41339. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41340. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41341. */
  41342. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41343. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41344. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41345. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41346. for (var i = 0; i < len; i++) {
  41347. var light = mesh._lightSources[i];
  41348. var iAsString = i.toString();
  41349. var scaledIntensity = light.getScaledIntensity();
  41350. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41351. MaterialHelper.BindLightProperties(light, effect, i);
  41352. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41353. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41354. if (defines["SPECULARTERM"]) {
  41355. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41356. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41357. }
  41358. // Shadows
  41359. if (scene.shadowsEnabled) {
  41360. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41361. }
  41362. light._uniformBuffer.update();
  41363. }
  41364. };
  41365. /**
  41366. * Binds the fog information from the scene to the effect for the given mesh.
  41367. * @param scene The scene the lights belongs to
  41368. * @param mesh The mesh we are binding the information to render
  41369. * @param effect The effect we are binding the data to
  41370. */
  41371. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41372. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41373. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41374. effect.setColor3("vFogColor", scene.fogColor);
  41375. }
  41376. };
  41377. /**
  41378. * Binds the bones information from the mesh to the effect.
  41379. * @param mesh The mesh we are binding the information to render
  41380. * @param effect The effect we are binding the data to
  41381. */
  41382. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41383. if (!effect || !mesh) {
  41384. return;
  41385. }
  41386. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41387. mesh.computeBonesUsingShaders = false;
  41388. }
  41389. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41390. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41391. if (matrices) {
  41392. effect.setMatrices("mBones", matrices);
  41393. }
  41394. }
  41395. };
  41396. /**
  41397. * Binds the morph targets information from the mesh to the effect.
  41398. * @param abstractMesh The mesh we are binding the information to render
  41399. * @param effect The effect we are binding the data to
  41400. */
  41401. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41402. var manager = abstractMesh.morphTargetManager;
  41403. if (!abstractMesh || !manager) {
  41404. return;
  41405. }
  41406. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41407. };
  41408. /**
  41409. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41410. * @param defines The generated defines used in the effect
  41411. * @param effect The effect we are binding the data to
  41412. * @param scene The scene we are willing to render with logarithmic scale for
  41413. */
  41414. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41415. if (defines["LOGARITHMICDEPTH"]) {
  41416. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41417. }
  41418. };
  41419. /**
  41420. * Binds the clip plane information from the scene to the effect.
  41421. * @param scene The scene the clip plane information are extracted from
  41422. * @param effect The effect we are binding the data to
  41423. */
  41424. MaterialHelper.BindClipPlane = function (effect, scene) {
  41425. if (scene.clipPlane) {
  41426. var clipPlane = scene.clipPlane;
  41427. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41428. }
  41429. };
  41430. return MaterialHelper;
  41431. }());
  41432. BABYLON.MaterialHelper = MaterialHelper;
  41433. })(BABYLON || (BABYLON = {}));
  41434. //# sourceMappingURL=babylon.materialHelper.js.map
  41435. var BABYLON;
  41436. (function (BABYLON) {
  41437. var PushMaterial = /** @class */ (function (_super) {
  41438. __extends(PushMaterial, _super);
  41439. function PushMaterial(name, scene) {
  41440. var _this = _super.call(this, name, scene) || this;
  41441. _this._normalMatrix = new BABYLON.Matrix();
  41442. _this.storeEffectOnSubMeshes = true;
  41443. return _this;
  41444. }
  41445. PushMaterial.prototype.getEffect = function () {
  41446. return this._activeEffect;
  41447. };
  41448. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41449. if (!mesh) {
  41450. return false;
  41451. }
  41452. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41453. return true;
  41454. }
  41455. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41456. };
  41457. /**
  41458. * Binds the given world matrix to the active effect
  41459. *
  41460. * @param world the matrix to bind
  41461. */
  41462. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41463. this._activeEffect.setMatrix("world", world);
  41464. };
  41465. /**
  41466. * Binds the given normal matrix to the active effect
  41467. *
  41468. * @param normalMatrix the matrix to bind
  41469. */
  41470. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41471. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41472. };
  41473. PushMaterial.prototype.bind = function (world, mesh) {
  41474. if (!mesh) {
  41475. return;
  41476. }
  41477. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41478. };
  41479. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41480. if (effect === void 0) { effect = null; }
  41481. _super.prototype._afterBind.call(this, mesh);
  41482. this.getScene()._cachedEffect = effect;
  41483. };
  41484. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41485. if (visibility === void 0) { visibility = 1; }
  41486. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41487. };
  41488. return PushMaterial;
  41489. }(BABYLON.Material));
  41490. BABYLON.PushMaterial = PushMaterial;
  41491. })(BABYLON || (BABYLON = {}));
  41492. //# sourceMappingURL=babylon.pushMaterial.js.map
  41493. var BABYLON;
  41494. (function (BABYLON) {
  41495. /** @hidden */
  41496. var StandardMaterialDefines = /** @class */ (function (_super) {
  41497. __extends(StandardMaterialDefines, _super);
  41498. function StandardMaterialDefines() {
  41499. var _this = _super.call(this) || this;
  41500. _this.MAINUV1 = false;
  41501. _this.MAINUV2 = false;
  41502. _this.DIFFUSE = false;
  41503. _this.DIFFUSEDIRECTUV = 0;
  41504. _this.AMBIENT = false;
  41505. _this.AMBIENTDIRECTUV = 0;
  41506. _this.OPACITY = false;
  41507. _this.OPACITYDIRECTUV = 0;
  41508. _this.OPACITYRGB = false;
  41509. _this.REFLECTION = false;
  41510. _this.EMISSIVE = false;
  41511. _this.EMISSIVEDIRECTUV = 0;
  41512. _this.SPECULAR = false;
  41513. _this.SPECULARDIRECTUV = 0;
  41514. _this.BUMP = false;
  41515. _this.BUMPDIRECTUV = 0;
  41516. _this.PARALLAX = false;
  41517. _this.PARALLAXOCCLUSION = false;
  41518. _this.SPECULAROVERALPHA = false;
  41519. _this.CLIPPLANE = false;
  41520. _this.ALPHATEST = false;
  41521. _this.DEPTHPREPASS = false;
  41522. _this.ALPHAFROMDIFFUSE = false;
  41523. _this.POINTSIZE = false;
  41524. _this.FOG = false;
  41525. _this.SPECULARTERM = false;
  41526. _this.DIFFUSEFRESNEL = false;
  41527. _this.OPACITYFRESNEL = false;
  41528. _this.REFLECTIONFRESNEL = false;
  41529. _this.REFRACTIONFRESNEL = false;
  41530. _this.EMISSIVEFRESNEL = false;
  41531. _this.FRESNEL = false;
  41532. _this.NORMAL = false;
  41533. _this.UV1 = false;
  41534. _this.UV2 = false;
  41535. _this.VERTEXCOLOR = false;
  41536. _this.VERTEXALPHA = false;
  41537. _this.NUM_BONE_INFLUENCERS = 0;
  41538. _this.BonesPerMesh = 0;
  41539. _this.INSTANCES = false;
  41540. _this.GLOSSINESS = false;
  41541. _this.ROUGHNESS = false;
  41542. _this.EMISSIVEASILLUMINATION = false;
  41543. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41544. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41545. _this.LIGHTMAP = false;
  41546. _this.LIGHTMAPDIRECTUV = 0;
  41547. _this.OBJECTSPACE_NORMALMAP = false;
  41548. _this.USELIGHTMAPASSHADOWMAP = false;
  41549. _this.REFLECTIONMAP_3D = false;
  41550. _this.REFLECTIONMAP_SPHERICAL = false;
  41551. _this.REFLECTIONMAP_PLANAR = false;
  41552. _this.REFLECTIONMAP_CUBIC = false;
  41553. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41554. _this.REFLECTIONMAP_PROJECTION = false;
  41555. _this.REFLECTIONMAP_SKYBOX = false;
  41556. _this.REFLECTIONMAP_EXPLICIT = false;
  41557. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41558. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41559. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41560. _this.INVERTCUBICMAP = false;
  41561. _this.LOGARITHMICDEPTH = false;
  41562. _this.REFRACTION = false;
  41563. _this.REFRACTIONMAP_3D = false;
  41564. _this.REFLECTIONOVERALPHA = false;
  41565. _this.TWOSIDEDLIGHTING = false;
  41566. _this.SHADOWFLOAT = false;
  41567. _this.MORPHTARGETS = false;
  41568. _this.MORPHTARGETS_NORMAL = false;
  41569. _this.MORPHTARGETS_TANGENT = false;
  41570. _this.NUM_MORPH_INFLUENCERS = 0;
  41571. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41572. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41573. _this.IMAGEPROCESSING = false;
  41574. _this.VIGNETTE = false;
  41575. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41576. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41577. _this.TONEMAPPING = false;
  41578. _this.TONEMAPPING_ACES = false;
  41579. _this.CONTRAST = false;
  41580. _this.COLORCURVES = false;
  41581. _this.COLORGRADING = false;
  41582. _this.COLORGRADING3D = false;
  41583. _this.SAMPLER3DGREENDEPTH = false;
  41584. _this.SAMPLER3DBGRMAP = false;
  41585. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41586. /**
  41587. * If the reflection texture on this material is in linear color space
  41588. * @hidden
  41589. */
  41590. _this.IS_REFLECTION_LINEAR = false;
  41591. /**
  41592. * If the refraction texture on this material is in linear color space
  41593. * @hidden
  41594. */
  41595. _this.IS_REFRACTION_LINEAR = false;
  41596. _this.EXPOSURE = false;
  41597. _this.rebuild();
  41598. return _this;
  41599. }
  41600. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41601. var modes = [
  41602. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41603. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41604. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41605. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41606. ];
  41607. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41608. var mode = modes_1[_i];
  41609. this[mode] = (mode === modeToEnable);
  41610. }
  41611. };
  41612. return StandardMaterialDefines;
  41613. }(BABYLON.MaterialDefines));
  41614. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41615. var StandardMaterial = /** @class */ (function (_super) {
  41616. __extends(StandardMaterial, _super);
  41617. function StandardMaterial(name, scene) {
  41618. var _this = _super.call(this, name, scene) || this;
  41619. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41620. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41621. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41622. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41623. _this.specularPower = 64;
  41624. _this._useAlphaFromDiffuseTexture = false;
  41625. _this._useEmissiveAsIllumination = false;
  41626. _this._linkEmissiveWithDiffuse = false;
  41627. _this._useSpecularOverAlpha = false;
  41628. _this._useReflectionOverAlpha = false;
  41629. _this._disableLighting = false;
  41630. _this._useObjectSpaceNormalMap = false;
  41631. _this._useParallax = false;
  41632. _this._useParallaxOcclusion = false;
  41633. _this.parallaxScaleBias = 0.05;
  41634. _this._roughness = 0;
  41635. _this.indexOfRefraction = 0.98;
  41636. _this.invertRefractionY = true;
  41637. /**
  41638. * Defines the alpha limits in alpha test mode
  41639. */
  41640. _this.alphaCutOff = 0.4;
  41641. _this._useLightmapAsShadowmap = false;
  41642. _this._useReflectionFresnelFromSpecular = false;
  41643. _this._useGlossinessFromSpecularMapAlpha = false;
  41644. _this._maxSimultaneousLights = 4;
  41645. /**
  41646. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41647. */
  41648. _this._invertNormalMapX = false;
  41649. /**
  41650. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41651. */
  41652. _this._invertNormalMapY = false;
  41653. /**
  41654. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41655. */
  41656. _this._twoSidedLighting = false;
  41657. _this._renderTargets = new BABYLON.SmartArray(16);
  41658. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41659. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41660. // Setup the default processing configuration to the scene.
  41661. _this._attachImageProcessingConfiguration(null);
  41662. _this.getRenderTargetTextures = function () {
  41663. _this._renderTargets.reset();
  41664. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41665. _this._renderTargets.push(_this._reflectionTexture);
  41666. }
  41667. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41668. _this._renderTargets.push(_this._refractionTexture);
  41669. }
  41670. return _this._renderTargets;
  41671. };
  41672. return _this;
  41673. }
  41674. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41675. /**
  41676. * Gets the image processing configuration used either in this material.
  41677. */
  41678. get: function () {
  41679. return this._imageProcessingConfiguration;
  41680. },
  41681. /**
  41682. * Sets the Default image processing configuration used either in the this material.
  41683. *
  41684. * If sets to null, the scene one is in use.
  41685. */
  41686. set: function (value) {
  41687. this._attachImageProcessingConfiguration(value);
  41688. // Ensure the effect will be rebuilt.
  41689. this._markAllSubMeshesAsTexturesDirty();
  41690. },
  41691. enumerable: true,
  41692. configurable: true
  41693. });
  41694. /**
  41695. * Attaches a new image processing configuration to the Standard Material.
  41696. * @param configuration
  41697. */
  41698. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41699. var _this = this;
  41700. if (configuration === this._imageProcessingConfiguration) {
  41701. return;
  41702. }
  41703. // Detaches observer.
  41704. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41705. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41706. }
  41707. // Pick the scene configuration if needed.
  41708. if (!configuration) {
  41709. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41710. }
  41711. else {
  41712. this._imageProcessingConfiguration = configuration;
  41713. }
  41714. // Attaches observer.
  41715. if (this._imageProcessingConfiguration) {
  41716. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41717. _this._markAllSubMeshesAsImageProcessingDirty();
  41718. });
  41719. }
  41720. };
  41721. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41722. /**
  41723. * Gets wether the color curves effect is enabled.
  41724. */
  41725. get: function () {
  41726. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41727. },
  41728. /**
  41729. * Sets wether the color curves effect is enabled.
  41730. */
  41731. set: function (value) {
  41732. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41733. },
  41734. enumerable: true,
  41735. configurable: true
  41736. });
  41737. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41738. /**
  41739. * Gets wether the color grading effect is enabled.
  41740. */
  41741. get: function () {
  41742. return this.imageProcessingConfiguration.colorGradingEnabled;
  41743. },
  41744. /**
  41745. * Gets wether the color grading effect is enabled.
  41746. */
  41747. set: function (value) {
  41748. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41749. },
  41750. enumerable: true,
  41751. configurable: true
  41752. });
  41753. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41754. /**
  41755. * Gets wether tonemapping is enabled or not.
  41756. */
  41757. get: function () {
  41758. return this._imageProcessingConfiguration.toneMappingEnabled;
  41759. },
  41760. /**
  41761. * Sets wether tonemapping is enabled or not
  41762. */
  41763. set: function (value) {
  41764. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41765. },
  41766. enumerable: true,
  41767. configurable: true
  41768. });
  41769. ;
  41770. ;
  41771. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41772. /**
  41773. * The camera exposure used on this material.
  41774. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41775. * This corresponds to a photographic exposure.
  41776. */
  41777. get: function () {
  41778. return this._imageProcessingConfiguration.exposure;
  41779. },
  41780. /**
  41781. * The camera exposure used on this material.
  41782. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41783. * This corresponds to a photographic exposure.
  41784. */
  41785. set: function (value) {
  41786. this._imageProcessingConfiguration.exposure = value;
  41787. },
  41788. enumerable: true,
  41789. configurable: true
  41790. });
  41791. ;
  41792. ;
  41793. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41794. /**
  41795. * Gets The camera contrast used on this material.
  41796. */
  41797. get: function () {
  41798. return this._imageProcessingConfiguration.contrast;
  41799. },
  41800. /**
  41801. * Sets The camera contrast used on this material.
  41802. */
  41803. set: function (value) {
  41804. this._imageProcessingConfiguration.contrast = value;
  41805. },
  41806. enumerable: true,
  41807. configurable: true
  41808. });
  41809. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41810. /**
  41811. * Gets the Color Grading 2D Lookup Texture.
  41812. */
  41813. get: function () {
  41814. return this._imageProcessingConfiguration.colorGradingTexture;
  41815. },
  41816. /**
  41817. * Sets the Color Grading 2D Lookup Texture.
  41818. */
  41819. set: function (value) {
  41820. this._imageProcessingConfiguration.colorGradingTexture = value;
  41821. },
  41822. enumerable: true,
  41823. configurable: true
  41824. });
  41825. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41826. /**
  41827. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41828. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41829. * 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;
  41830. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41831. */
  41832. get: function () {
  41833. return this._imageProcessingConfiguration.colorCurves;
  41834. },
  41835. /**
  41836. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41837. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41838. * 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;
  41839. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41840. */
  41841. set: function (value) {
  41842. this._imageProcessingConfiguration.colorCurves = value;
  41843. },
  41844. enumerable: true,
  41845. configurable: true
  41846. });
  41847. StandardMaterial.prototype.getClassName = function () {
  41848. return "StandardMaterial";
  41849. };
  41850. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41851. get: function () {
  41852. return this._useLogarithmicDepth;
  41853. },
  41854. set: function (value) {
  41855. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41856. this._markAllSubMeshesAsMiscDirty();
  41857. },
  41858. enumerable: true,
  41859. configurable: true
  41860. });
  41861. StandardMaterial.prototype.needAlphaBlending = function () {
  41862. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41863. };
  41864. StandardMaterial.prototype.needAlphaTesting = function () {
  41865. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41866. };
  41867. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41868. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41869. };
  41870. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41871. return this._diffuseTexture;
  41872. };
  41873. /**
  41874. * Child classes can use it to update shaders
  41875. */
  41876. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41877. if (useInstances === void 0) { useInstances = false; }
  41878. if (subMesh.effect && this.isFrozen) {
  41879. if (this._wasPreviouslyReady) {
  41880. return true;
  41881. }
  41882. }
  41883. if (!subMesh._materialDefines) {
  41884. subMesh._materialDefines = new StandardMaterialDefines();
  41885. }
  41886. var scene = this.getScene();
  41887. var defines = subMesh._materialDefines;
  41888. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41889. if (defines._renderId === scene.getRenderId()) {
  41890. return true;
  41891. }
  41892. }
  41893. var engine = scene.getEngine();
  41894. // Lights
  41895. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41896. // Textures
  41897. if (defines._areTexturesDirty) {
  41898. defines._needUVs = false;
  41899. defines.MAINUV1 = false;
  41900. defines.MAINUV2 = false;
  41901. if (scene.texturesEnabled) {
  41902. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41903. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41904. return false;
  41905. }
  41906. else {
  41907. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41908. }
  41909. }
  41910. else {
  41911. defines.DIFFUSE = false;
  41912. }
  41913. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41914. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41915. return false;
  41916. }
  41917. else {
  41918. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41919. }
  41920. }
  41921. else {
  41922. defines.AMBIENT = false;
  41923. }
  41924. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41925. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41926. return false;
  41927. }
  41928. else {
  41929. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41930. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41931. }
  41932. }
  41933. else {
  41934. defines.OPACITY = false;
  41935. }
  41936. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41937. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41938. return false;
  41939. }
  41940. else {
  41941. defines._needNormals = true;
  41942. defines.REFLECTION = true;
  41943. defines.ROUGHNESS = (this._roughness > 0);
  41944. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41945. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41946. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41947. switch (this._reflectionTexture.coordinatesMode) {
  41948. case BABYLON.Texture.EXPLICIT_MODE:
  41949. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41950. break;
  41951. case BABYLON.Texture.PLANAR_MODE:
  41952. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41953. break;
  41954. case BABYLON.Texture.PROJECTION_MODE:
  41955. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41956. break;
  41957. case BABYLON.Texture.SKYBOX_MODE:
  41958. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41959. break;
  41960. case BABYLON.Texture.SPHERICAL_MODE:
  41961. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41962. break;
  41963. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41964. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41965. break;
  41966. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41967. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41968. break;
  41969. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41970. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41971. break;
  41972. case BABYLON.Texture.CUBIC_MODE:
  41973. case BABYLON.Texture.INVCUBIC_MODE:
  41974. default:
  41975. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41976. break;
  41977. }
  41978. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41979. }
  41980. }
  41981. else {
  41982. defines.REFLECTION = false;
  41983. }
  41984. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41985. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41986. return false;
  41987. }
  41988. else {
  41989. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41990. }
  41991. }
  41992. else {
  41993. defines.EMISSIVE = false;
  41994. }
  41995. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41996. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41997. return false;
  41998. }
  41999. else {
  42000. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42001. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42002. }
  42003. }
  42004. else {
  42005. defines.LIGHTMAP = false;
  42006. }
  42007. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42008. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42009. return false;
  42010. }
  42011. else {
  42012. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42013. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42014. }
  42015. }
  42016. else {
  42017. defines.SPECULAR = false;
  42018. }
  42019. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42020. // Bump texure can not be not blocking.
  42021. if (!this._bumpTexture.isReady()) {
  42022. return false;
  42023. }
  42024. else {
  42025. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42026. defines.PARALLAX = this._useParallax;
  42027. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42028. }
  42029. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42030. }
  42031. else {
  42032. defines.BUMP = false;
  42033. }
  42034. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42035. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42036. return false;
  42037. }
  42038. else {
  42039. defines._needUVs = true;
  42040. defines.REFRACTION = true;
  42041. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42042. }
  42043. }
  42044. else {
  42045. defines.REFRACTION = false;
  42046. }
  42047. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42048. }
  42049. else {
  42050. defines.DIFFUSE = false;
  42051. defines.AMBIENT = false;
  42052. defines.OPACITY = false;
  42053. defines.REFLECTION = false;
  42054. defines.EMISSIVE = false;
  42055. defines.LIGHTMAP = false;
  42056. defines.BUMP = false;
  42057. defines.REFRACTION = false;
  42058. }
  42059. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42060. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42061. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42062. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42063. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42064. }
  42065. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42066. if (!this._imageProcessingConfiguration.isReady()) {
  42067. return false;
  42068. }
  42069. this._imageProcessingConfiguration.prepareDefines(defines);
  42070. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42071. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42072. }
  42073. if (defines._areFresnelDirty) {
  42074. if (StandardMaterial.FresnelEnabled) {
  42075. // Fresnel
  42076. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42077. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42078. this._reflectionFresnelParameters) {
  42079. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42080. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42081. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42082. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42083. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42084. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42085. defines._needNormals = true;
  42086. defines.FRESNEL = true;
  42087. }
  42088. }
  42089. else {
  42090. defines.FRESNEL = false;
  42091. }
  42092. }
  42093. // Misc.
  42094. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42095. // Attribs
  42096. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42097. // Values that need to be evaluated on every frame
  42098. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42099. // Get correct effect
  42100. if (defines.isDirty) {
  42101. defines.markAsProcessed();
  42102. scene.resetCachedMaterial();
  42103. // Fallbacks
  42104. var fallbacks = new BABYLON.EffectFallbacks();
  42105. if (defines.REFLECTION) {
  42106. fallbacks.addFallback(0, "REFLECTION");
  42107. }
  42108. if (defines.SPECULAR) {
  42109. fallbacks.addFallback(0, "SPECULAR");
  42110. }
  42111. if (defines.BUMP) {
  42112. fallbacks.addFallback(0, "BUMP");
  42113. }
  42114. if (defines.PARALLAX) {
  42115. fallbacks.addFallback(1, "PARALLAX");
  42116. }
  42117. if (defines.PARALLAXOCCLUSION) {
  42118. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42119. }
  42120. if (defines.SPECULAROVERALPHA) {
  42121. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42122. }
  42123. if (defines.FOG) {
  42124. fallbacks.addFallback(1, "FOG");
  42125. }
  42126. if (defines.POINTSIZE) {
  42127. fallbacks.addFallback(0, "POINTSIZE");
  42128. }
  42129. if (defines.LOGARITHMICDEPTH) {
  42130. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42131. }
  42132. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42133. if (defines.SPECULARTERM) {
  42134. fallbacks.addFallback(0, "SPECULARTERM");
  42135. }
  42136. if (defines.DIFFUSEFRESNEL) {
  42137. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42138. }
  42139. if (defines.OPACITYFRESNEL) {
  42140. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42141. }
  42142. if (defines.REFLECTIONFRESNEL) {
  42143. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42144. }
  42145. if (defines.EMISSIVEFRESNEL) {
  42146. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42147. }
  42148. if (defines.FRESNEL) {
  42149. fallbacks.addFallback(4, "FRESNEL");
  42150. }
  42151. //Attributes
  42152. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42153. if (defines.NORMAL) {
  42154. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42155. }
  42156. if (defines.UV1) {
  42157. attribs.push(BABYLON.VertexBuffer.UVKind);
  42158. }
  42159. if (defines.UV2) {
  42160. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42161. }
  42162. if (defines.VERTEXCOLOR) {
  42163. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42164. }
  42165. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42166. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42167. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42168. var shaderName = "default";
  42169. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42170. "vFogInfos", "vFogColor", "pointSize",
  42171. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42172. "mBones",
  42173. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42174. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42175. "vReflectionPosition", "vReflectionSize",
  42176. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42177. ];
  42178. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42179. var uniformBuffers = ["Material", "Scene"];
  42180. if (BABYLON.ImageProcessingConfiguration) {
  42181. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42182. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42183. }
  42184. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42185. uniformsNames: uniforms,
  42186. uniformBuffersNames: uniformBuffers,
  42187. samplers: samplers,
  42188. defines: defines,
  42189. maxSimultaneousLights: this._maxSimultaneousLights
  42190. });
  42191. if (this.customShaderNameResolve) {
  42192. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42193. }
  42194. var join = defines.toString();
  42195. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42196. attributes: attribs,
  42197. uniformsNames: uniforms,
  42198. uniformBuffersNames: uniformBuffers,
  42199. samplers: samplers,
  42200. defines: join,
  42201. fallbacks: fallbacks,
  42202. onCompiled: this.onCompiled,
  42203. onError: this.onError,
  42204. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42205. }, engine), defines);
  42206. this.buildUniformLayout();
  42207. }
  42208. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42209. return false;
  42210. }
  42211. defines._renderId = scene.getRenderId();
  42212. this._wasPreviouslyReady = true;
  42213. return true;
  42214. };
  42215. StandardMaterial.prototype.buildUniformLayout = function () {
  42216. // Order is important !
  42217. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42218. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42219. this._uniformBuffer.addUniform("opacityParts", 4);
  42220. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42221. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42222. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42223. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42224. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42225. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42226. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42227. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42228. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42229. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42230. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42231. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42232. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42233. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42234. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42235. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42236. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42237. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42238. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42239. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42240. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42241. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42242. this._uniformBuffer.addUniform("specularMatrix", 16);
  42243. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42244. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42245. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42246. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42247. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42248. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42249. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42250. this._uniformBuffer.addUniform("pointSize", 1);
  42251. this._uniformBuffer.create();
  42252. };
  42253. StandardMaterial.prototype.unbind = function () {
  42254. if (this._activeEffect) {
  42255. var needFlag = false;
  42256. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42257. this._activeEffect.setTexture("reflection2DSampler", null);
  42258. needFlag = true;
  42259. }
  42260. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42261. this._activeEffect.setTexture("refraction2DSampler", null);
  42262. needFlag = true;
  42263. }
  42264. if (needFlag) {
  42265. this._markAllSubMeshesAsTexturesDirty();
  42266. }
  42267. }
  42268. _super.prototype.unbind.call(this);
  42269. };
  42270. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42271. var scene = this.getScene();
  42272. var defines = subMesh._materialDefines;
  42273. if (!defines) {
  42274. return;
  42275. }
  42276. var effect = subMesh.effect;
  42277. if (!effect) {
  42278. return;
  42279. }
  42280. this._activeEffect = effect;
  42281. // Matrices
  42282. this.bindOnlyWorldMatrix(world);
  42283. // Normal Matrix
  42284. if (defines.OBJECTSPACE_NORMALMAP) {
  42285. world.toNormalMatrix(this._normalMatrix);
  42286. this.bindOnlyNormalMatrix(this._normalMatrix);
  42287. }
  42288. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42289. // Bones
  42290. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42291. if (mustRebind) {
  42292. this._uniformBuffer.bindToEffect(effect, "Material");
  42293. this.bindViewProjection(effect);
  42294. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42295. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42296. // Fresnel
  42297. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42298. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42299. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42300. }
  42301. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42302. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42303. }
  42304. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42305. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42306. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42307. }
  42308. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42309. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42310. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42311. }
  42312. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42313. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42314. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42315. }
  42316. }
  42317. // Textures
  42318. if (scene.texturesEnabled) {
  42319. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42320. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42321. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42322. if (this._diffuseTexture.hasAlpha) {
  42323. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42324. }
  42325. }
  42326. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42327. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42328. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42329. }
  42330. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42331. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42332. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42333. }
  42334. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42335. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42336. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42337. if (this._reflectionTexture.boundingBoxSize) {
  42338. var cubeTexture = this._reflectionTexture;
  42339. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42340. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42341. }
  42342. }
  42343. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42344. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42345. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42346. }
  42347. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42348. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42349. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42350. }
  42351. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42352. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42353. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42354. }
  42355. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42356. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42357. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42358. if (scene._mirroredCameraPosition) {
  42359. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42360. }
  42361. else {
  42362. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42363. }
  42364. }
  42365. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42366. var depth = 1.0;
  42367. if (!this._refractionTexture.isCube) {
  42368. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42369. if (this._refractionTexture.depth) {
  42370. depth = this._refractionTexture.depth;
  42371. }
  42372. }
  42373. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42374. }
  42375. }
  42376. // Point size
  42377. if (this.pointsCloud) {
  42378. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42379. }
  42380. if (defines.SPECULARTERM) {
  42381. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42382. }
  42383. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42384. // Diffuse
  42385. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42386. }
  42387. // Textures
  42388. if (scene.texturesEnabled) {
  42389. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42390. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42391. }
  42392. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42393. effect.setTexture("ambientSampler", this._ambientTexture);
  42394. }
  42395. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42396. effect.setTexture("opacitySampler", this._opacityTexture);
  42397. }
  42398. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42399. if (this._reflectionTexture.isCube) {
  42400. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42401. }
  42402. else {
  42403. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42404. }
  42405. }
  42406. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42407. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42408. }
  42409. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42410. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42411. }
  42412. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42413. effect.setTexture("specularSampler", this._specularTexture);
  42414. }
  42415. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42416. effect.setTexture("bumpSampler", this._bumpTexture);
  42417. }
  42418. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42419. var depth = 1.0;
  42420. if (this._refractionTexture.isCube) {
  42421. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42422. }
  42423. else {
  42424. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42425. }
  42426. }
  42427. }
  42428. // Clip plane
  42429. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42430. // Colors
  42431. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42432. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42433. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42434. }
  42435. if (mustRebind || !this.isFrozen) {
  42436. // Lights
  42437. if (scene.lightsEnabled && !this._disableLighting) {
  42438. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42439. }
  42440. // View
  42441. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42442. this.bindView(effect);
  42443. }
  42444. // Fog
  42445. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42446. // Morph targets
  42447. if (defines.NUM_MORPH_INFLUENCERS) {
  42448. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42449. }
  42450. // Log. depth
  42451. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42452. // image processing
  42453. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42454. this._imageProcessingConfiguration.bind(this._activeEffect);
  42455. }
  42456. }
  42457. this._uniformBuffer.update();
  42458. this._afterBind(mesh, this._activeEffect);
  42459. };
  42460. StandardMaterial.prototype.getAnimatables = function () {
  42461. var results = [];
  42462. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42463. results.push(this._diffuseTexture);
  42464. }
  42465. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42466. results.push(this._ambientTexture);
  42467. }
  42468. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42469. results.push(this._opacityTexture);
  42470. }
  42471. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42472. results.push(this._reflectionTexture);
  42473. }
  42474. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42475. results.push(this._emissiveTexture);
  42476. }
  42477. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42478. results.push(this._specularTexture);
  42479. }
  42480. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42481. results.push(this._bumpTexture);
  42482. }
  42483. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42484. results.push(this._lightmapTexture);
  42485. }
  42486. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42487. results.push(this._refractionTexture);
  42488. }
  42489. return results;
  42490. };
  42491. StandardMaterial.prototype.getActiveTextures = function () {
  42492. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42493. if (this._diffuseTexture) {
  42494. activeTextures.push(this._diffuseTexture);
  42495. }
  42496. if (this._ambientTexture) {
  42497. activeTextures.push(this._ambientTexture);
  42498. }
  42499. if (this._opacityTexture) {
  42500. activeTextures.push(this._opacityTexture);
  42501. }
  42502. if (this._reflectionTexture) {
  42503. activeTextures.push(this._reflectionTexture);
  42504. }
  42505. if (this._emissiveTexture) {
  42506. activeTextures.push(this._emissiveTexture);
  42507. }
  42508. if (this._specularTexture) {
  42509. activeTextures.push(this._specularTexture);
  42510. }
  42511. if (this._bumpTexture) {
  42512. activeTextures.push(this._bumpTexture);
  42513. }
  42514. if (this._lightmapTexture) {
  42515. activeTextures.push(this._lightmapTexture);
  42516. }
  42517. if (this._refractionTexture) {
  42518. activeTextures.push(this._refractionTexture);
  42519. }
  42520. return activeTextures;
  42521. };
  42522. StandardMaterial.prototype.hasTexture = function (texture) {
  42523. if (_super.prototype.hasTexture.call(this, texture)) {
  42524. return true;
  42525. }
  42526. if (this._diffuseTexture === texture) {
  42527. return true;
  42528. }
  42529. if (this._ambientTexture === texture) {
  42530. return true;
  42531. }
  42532. if (this._opacityTexture === texture) {
  42533. return true;
  42534. }
  42535. if (this._reflectionTexture === texture) {
  42536. return true;
  42537. }
  42538. if (this._emissiveTexture === texture) {
  42539. return true;
  42540. }
  42541. if (this._specularTexture === texture) {
  42542. return true;
  42543. }
  42544. if (this._bumpTexture === texture) {
  42545. return true;
  42546. }
  42547. if (this._lightmapTexture === texture) {
  42548. return true;
  42549. }
  42550. if (this._refractionTexture === texture) {
  42551. return true;
  42552. }
  42553. return false;
  42554. };
  42555. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42556. if (forceDisposeTextures) {
  42557. if (this._diffuseTexture) {
  42558. this._diffuseTexture.dispose();
  42559. }
  42560. if (this._ambientTexture) {
  42561. this._ambientTexture.dispose();
  42562. }
  42563. if (this._opacityTexture) {
  42564. this._opacityTexture.dispose();
  42565. }
  42566. if (this._reflectionTexture) {
  42567. this._reflectionTexture.dispose();
  42568. }
  42569. if (this._emissiveTexture) {
  42570. this._emissiveTexture.dispose();
  42571. }
  42572. if (this._specularTexture) {
  42573. this._specularTexture.dispose();
  42574. }
  42575. if (this._bumpTexture) {
  42576. this._bumpTexture.dispose();
  42577. }
  42578. if (this._lightmapTexture) {
  42579. this._lightmapTexture.dispose();
  42580. }
  42581. if (this._refractionTexture) {
  42582. this._refractionTexture.dispose();
  42583. }
  42584. }
  42585. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42586. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42587. }
  42588. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42589. };
  42590. StandardMaterial.prototype.clone = function (name) {
  42591. var _this = this;
  42592. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42593. result.name = name;
  42594. result.id = name;
  42595. return result;
  42596. };
  42597. StandardMaterial.prototype.serialize = function () {
  42598. return BABYLON.SerializationHelper.Serialize(this);
  42599. };
  42600. // Statics
  42601. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42602. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42603. };
  42604. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42605. get: function () {
  42606. return StandardMaterial._DiffuseTextureEnabled;
  42607. },
  42608. set: function (value) {
  42609. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42610. return;
  42611. }
  42612. StandardMaterial._DiffuseTextureEnabled = value;
  42613. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42614. },
  42615. enumerable: true,
  42616. configurable: true
  42617. });
  42618. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42619. get: function () {
  42620. return StandardMaterial._AmbientTextureEnabled;
  42621. },
  42622. set: function (value) {
  42623. if (StandardMaterial._AmbientTextureEnabled === value) {
  42624. return;
  42625. }
  42626. StandardMaterial._AmbientTextureEnabled = value;
  42627. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42628. },
  42629. enumerable: true,
  42630. configurable: true
  42631. });
  42632. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42633. get: function () {
  42634. return StandardMaterial._OpacityTextureEnabled;
  42635. },
  42636. set: function (value) {
  42637. if (StandardMaterial._OpacityTextureEnabled === value) {
  42638. return;
  42639. }
  42640. StandardMaterial._OpacityTextureEnabled = value;
  42641. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42642. },
  42643. enumerable: true,
  42644. configurable: true
  42645. });
  42646. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42647. get: function () {
  42648. return StandardMaterial._ReflectionTextureEnabled;
  42649. },
  42650. set: function (value) {
  42651. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42652. return;
  42653. }
  42654. StandardMaterial._ReflectionTextureEnabled = value;
  42655. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42656. },
  42657. enumerable: true,
  42658. configurable: true
  42659. });
  42660. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42661. get: function () {
  42662. return StandardMaterial._EmissiveTextureEnabled;
  42663. },
  42664. set: function (value) {
  42665. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42666. return;
  42667. }
  42668. StandardMaterial._EmissiveTextureEnabled = value;
  42669. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42670. },
  42671. enumerable: true,
  42672. configurable: true
  42673. });
  42674. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42675. get: function () {
  42676. return StandardMaterial._SpecularTextureEnabled;
  42677. },
  42678. set: function (value) {
  42679. if (StandardMaterial._SpecularTextureEnabled === value) {
  42680. return;
  42681. }
  42682. StandardMaterial._SpecularTextureEnabled = value;
  42683. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42684. },
  42685. enumerable: true,
  42686. configurable: true
  42687. });
  42688. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42689. get: function () {
  42690. return StandardMaterial._BumpTextureEnabled;
  42691. },
  42692. set: function (value) {
  42693. if (StandardMaterial._BumpTextureEnabled === value) {
  42694. return;
  42695. }
  42696. StandardMaterial._BumpTextureEnabled = value;
  42697. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42698. },
  42699. enumerable: true,
  42700. configurable: true
  42701. });
  42702. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42703. get: function () {
  42704. return StandardMaterial._LightmapTextureEnabled;
  42705. },
  42706. set: function (value) {
  42707. if (StandardMaterial._LightmapTextureEnabled === value) {
  42708. return;
  42709. }
  42710. StandardMaterial._LightmapTextureEnabled = value;
  42711. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42712. },
  42713. enumerable: true,
  42714. configurable: true
  42715. });
  42716. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42717. get: function () {
  42718. return StandardMaterial._RefractionTextureEnabled;
  42719. },
  42720. set: function (value) {
  42721. if (StandardMaterial._RefractionTextureEnabled === value) {
  42722. return;
  42723. }
  42724. StandardMaterial._RefractionTextureEnabled = value;
  42725. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42726. },
  42727. enumerable: true,
  42728. configurable: true
  42729. });
  42730. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42731. get: function () {
  42732. return StandardMaterial._ColorGradingTextureEnabled;
  42733. },
  42734. set: function (value) {
  42735. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42736. return;
  42737. }
  42738. StandardMaterial._ColorGradingTextureEnabled = value;
  42739. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42740. },
  42741. enumerable: true,
  42742. configurable: true
  42743. });
  42744. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42745. get: function () {
  42746. return StandardMaterial._FresnelEnabled;
  42747. },
  42748. set: function (value) {
  42749. if (StandardMaterial._FresnelEnabled === value) {
  42750. return;
  42751. }
  42752. StandardMaterial._FresnelEnabled = value;
  42753. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42754. },
  42755. enumerable: true,
  42756. configurable: true
  42757. });
  42758. // Flags used to enable or disable a type of texture for all Standard Materials
  42759. StandardMaterial._DiffuseTextureEnabled = true;
  42760. StandardMaterial._AmbientTextureEnabled = true;
  42761. StandardMaterial._OpacityTextureEnabled = true;
  42762. StandardMaterial._ReflectionTextureEnabled = true;
  42763. StandardMaterial._EmissiveTextureEnabled = true;
  42764. StandardMaterial._SpecularTextureEnabled = true;
  42765. StandardMaterial._BumpTextureEnabled = true;
  42766. StandardMaterial._LightmapTextureEnabled = true;
  42767. StandardMaterial._RefractionTextureEnabled = true;
  42768. StandardMaterial._ColorGradingTextureEnabled = true;
  42769. StandardMaterial._FresnelEnabled = true;
  42770. __decorate([
  42771. BABYLON.serializeAsTexture("diffuseTexture")
  42772. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42773. __decorate([
  42774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42775. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42776. __decorate([
  42777. BABYLON.serializeAsTexture("ambientTexture")
  42778. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42779. __decorate([
  42780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42781. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42782. __decorate([
  42783. BABYLON.serializeAsTexture("opacityTexture")
  42784. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42785. __decorate([
  42786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42787. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42788. __decorate([
  42789. BABYLON.serializeAsTexture("reflectionTexture")
  42790. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42791. __decorate([
  42792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42793. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42794. __decorate([
  42795. BABYLON.serializeAsTexture("emissiveTexture")
  42796. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42797. __decorate([
  42798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42799. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42800. __decorate([
  42801. BABYLON.serializeAsTexture("specularTexture")
  42802. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42803. __decorate([
  42804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42805. ], StandardMaterial.prototype, "specularTexture", void 0);
  42806. __decorate([
  42807. BABYLON.serializeAsTexture("bumpTexture")
  42808. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42809. __decorate([
  42810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42811. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42812. __decorate([
  42813. BABYLON.serializeAsTexture("lightmapTexture")
  42814. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42815. __decorate([
  42816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42817. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42818. __decorate([
  42819. BABYLON.serializeAsTexture("refractionTexture")
  42820. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42821. __decorate([
  42822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42823. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42824. __decorate([
  42825. BABYLON.serializeAsColor3("ambient")
  42826. ], StandardMaterial.prototype, "ambientColor", void 0);
  42827. __decorate([
  42828. BABYLON.serializeAsColor3("diffuse")
  42829. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42830. __decorate([
  42831. BABYLON.serializeAsColor3("specular")
  42832. ], StandardMaterial.prototype, "specularColor", void 0);
  42833. __decorate([
  42834. BABYLON.serializeAsColor3("emissive")
  42835. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42836. __decorate([
  42837. BABYLON.serialize()
  42838. ], StandardMaterial.prototype, "specularPower", void 0);
  42839. __decorate([
  42840. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42841. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42842. __decorate([
  42843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42844. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42845. __decorate([
  42846. BABYLON.serialize("useEmissiveAsIllumination")
  42847. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42848. __decorate([
  42849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42850. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42851. __decorate([
  42852. BABYLON.serialize("linkEmissiveWithDiffuse")
  42853. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42854. __decorate([
  42855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42856. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42857. __decorate([
  42858. BABYLON.serialize("useSpecularOverAlpha")
  42859. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42860. __decorate([
  42861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42862. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42863. __decorate([
  42864. BABYLON.serialize("useReflectionOverAlpha")
  42865. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42866. __decorate([
  42867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42868. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42869. __decorate([
  42870. BABYLON.serialize("disableLighting")
  42871. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42872. __decorate([
  42873. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42874. ], StandardMaterial.prototype, "disableLighting", void 0);
  42875. __decorate([
  42876. BABYLON.serialize("useObjectSpaceNormalMap")
  42877. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42878. __decorate([
  42879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42880. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42881. __decorate([
  42882. BABYLON.serialize("useParallax")
  42883. ], StandardMaterial.prototype, "_useParallax", void 0);
  42884. __decorate([
  42885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42886. ], StandardMaterial.prototype, "useParallax", void 0);
  42887. __decorate([
  42888. BABYLON.serialize("useParallaxOcclusion")
  42889. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42890. __decorate([
  42891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42892. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42893. __decorate([
  42894. BABYLON.serialize()
  42895. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42896. __decorate([
  42897. BABYLON.serialize("roughness")
  42898. ], StandardMaterial.prototype, "_roughness", void 0);
  42899. __decorate([
  42900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42901. ], StandardMaterial.prototype, "roughness", void 0);
  42902. __decorate([
  42903. BABYLON.serialize()
  42904. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42905. __decorate([
  42906. BABYLON.serialize()
  42907. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42908. __decorate([
  42909. BABYLON.serialize()
  42910. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42911. __decorate([
  42912. BABYLON.serialize("useLightmapAsShadowmap")
  42913. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42914. __decorate([
  42915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42916. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42917. __decorate([
  42918. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42919. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42920. __decorate([
  42921. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42922. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42923. __decorate([
  42924. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42925. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42926. __decorate([
  42927. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42928. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42929. __decorate([
  42930. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42931. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42932. __decorate([
  42933. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42934. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42935. __decorate([
  42936. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42937. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42938. __decorate([
  42939. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42940. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42941. __decorate([
  42942. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42943. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42944. __decorate([
  42945. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42946. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42947. __decorate([
  42948. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42949. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42950. __decorate([
  42951. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42952. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42953. __decorate([
  42954. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42955. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42956. __decorate([
  42957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42958. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42959. __decorate([
  42960. BABYLON.serialize("maxSimultaneousLights")
  42961. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42962. __decorate([
  42963. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42964. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42965. __decorate([
  42966. BABYLON.serialize("invertNormalMapX")
  42967. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42968. __decorate([
  42969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42970. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42971. __decorate([
  42972. BABYLON.serialize("invertNormalMapY")
  42973. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42974. __decorate([
  42975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42976. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42977. __decorate([
  42978. BABYLON.serialize("twoSidedLighting")
  42979. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42980. __decorate([
  42981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42982. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42983. __decorate([
  42984. BABYLON.serialize()
  42985. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42986. return StandardMaterial;
  42987. }(BABYLON.PushMaterial));
  42988. BABYLON.StandardMaterial = StandardMaterial;
  42989. })(BABYLON || (BABYLON = {}));
  42990. //# sourceMappingURL=babylon.standardMaterial.js.map
  42991. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\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","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\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};"};
  42992. var BABYLON;
  42993. (function (BABYLON) {
  42994. /**
  42995. * Class representing spherical polynomial coefficients to the 3rd degree
  42996. */
  42997. var SphericalPolynomial = /** @class */ (function () {
  42998. function SphericalPolynomial() {
  42999. /**
  43000. * The x coefficients of the spherical polynomial
  43001. */
  43002. this.x = BABYLON.Vector3.Zero();
  43003. /**
  43004. * The y coefficients of the spherical polynomial
  43005. */
  43006. this.y = BABYLON.Vector3.Zero();
  43007. /**
  43008. * The z coefficients of the spherical polynomial
  43009. */
  43010. this.z = BABYLON.Vector3.Zero();
  43011. /**
  43012. * The xx coefficients of the spherical polynomial
  43013. */
  43014. this.xx = BABYLON.Vector3.Zero();
  43015. /**
  43016. * The yy coefficients of the spherical polynomial
  43017. */
  43018. this.yy = BABYLON.Vector3.Zero();
  43019. /**
  43020. * The zz coefficients of the spherical polynomial
  43021. */
  43022. this.zz = BABYLON.Vector3.Zero();
  43023. /**
  43024. * The xy coefficients of the spherical polynomial
  43025. */
  43026. this.xy = BABYLON.Vector3.Zero();
  43027. /**
  43028. * The yz coefficients of the spherical polynomial
  43029. */
  43030. this.yz = BABYLON.Vector3.Zero();
  43031. /**
  43032. * The zx coefficients of the spherical polynomial
  43033. */
  43034. this.zx = BABYLON.Vector3.Zero();
  43035. }
  43036. /**
  43037. * Adds an ambient color to the spherical polynomial
  43038. * @param color the color to add
  43039. */
  43040. SphericalPolynomial.prototype.addAmbient = function (color) {
  43041. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43042. this.xx = this.xx.add(colorVector);
  43043. this.yy = this.yy.add(colorVector);
  43044. this.zz = this.zz.add(colorVector);
  43045. };
  43046. /**
  43047. * Scales the spherical polynomial by the given amount
  43048. * @param scale the amount to scale
  43049. */
  43050. SphericalPolynomial.prototype.scale = function (scale) {
  43051. this.x = this.x.scale(scale);
  43052. this.y = this.y.scale(scale);
  43053. this.z = this.z.scale(scale);
  43054. this.xx = this.xx.scale(scale);
  43055. this.yy = this.yy.scale(scale);
  43056. this.zz = this.zz.scale(scale);
  43057. this.yz = this.yz.scale(scale);
  43058. this.zx = this.zx.scale(scale);
  43059. this.xy = this.xy.scale(scale);
  43060. };
  43061. /**
  43062. * Gets the spherical polynomial from harmonics
  43063. * @param harmonics the spherical harmonics
  43064. * @returns the spherical polynomial
  43065. */
  43066. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43067. var result = new SphericalPolynomial();
  43068. result.x = harmonics.l11.scale(1.02333);
  43069. result.y = harmonics.l1_1.scale(1.02333);
  43070. result.z = harmonics.l10.scale(1.02333);
  43071. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43072. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43073. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43074. result.yz = harmonics.l2_1.scale(0.858086);
  43075. result.zx = harmonics.l21.scale(0.858086);
  43076. result.xy = harmonics.l2_2.scale(0.858086);
  43077. result.scale(1.0 / Math.PI);
  43078. return result;
  43079. };
  43080. /**
  43081. * Constructs a spherical polynomial from an array.
  43082. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43083. * @returns the spherical polynomial
  43084. */
  43085. SphericalPolynomial.FromArray = function (data) {
  43086. var sp = new SphericalPolynomial();
  43087. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43088. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43089. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43090. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43091. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43092. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43093. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43094. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43095. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43096. return sp;
  43097. };
  43098. return SphericalPolynomial;
  43099. }());
  43100. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43101. /**
  43102. * Class representing spherical harmonics coefficients to the 3rd degree
  43103. */
  43104. var SphericalHarmonics = /** @class */ (function () {
  43105. function SphericalHarmonics() {
  43106. /**
  43107. * The l0,0 coefficients of the spherical harmonics
  43108. */
  43109. this.l00 = BABYLON.Vector3.Zero();
  43110. /**
  43111. * The l1,-1 coefficients of the spherical harmonics
  43112. */
  43113. this.l1_1 = BABYLON.Vector3.Zero();
  43114. /**
  43115. * The l1,0 coefficients of the spherical harmonics
  43116. */
  43117. this.l10 = BABYLON.Vector3.Zero();
  43118. /**
  43119. * The l1,1 coefficients of the spherical harmonics
  43120. */
  43121. this.l11 = BABYLON.Vector3.Zero();
  43122. /**
  43123. * The l2,-2 coefficients of the spherical harmonics
  43124. */
  43125. this.l2_2 = BABYLON.Vector3.Zero();
  43126. /**
  43127. * The l2,-1 coefficients of the spherical harmonics
  43128. */
  43129. this.l2_1 = BABYLON.Vector3.Zero();
  43130. /**
  43131. * The l2,0 coefficients of the spherical harmonics
  43132. */
  43133. this.l20 = BABYLON.Vector3.Zero();
  43134. /**
  43135. * The l2,1 coefficients of the spherical harmonics
  43136. */
  43137. this.l21 = BABYLON.Vector3.Zero();
  43138. /**
  43139. * The l2,2 coefficients of the spherical harmonics
  43140. */
  43141. this.lL22 = BABYLON.Vector3.Zero();
  43142. }
  43143. /**
  43144. * Adds a light to the spherical harmonics
  43145. * @param direction the direction of the light
  43146. * @param color the color of the light
  43147. * @param deltaSolidAngle the delta solid angle of the light
  43148. */
  43149. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43150. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43151. var c = colorVector.scale(deltaSolidAngle);
  43152. this.l00 = this.l00.add(c.scale(0.282095));
  43153. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43154. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43155. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43156. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43157. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43158. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43159. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43160. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43161. };
  43162. /**
  43163. * Scales the spherical harmonics by the given amount
  43164. * @param scale the amount to scale
  43165. */
  43166. SphericalHarmonics.prototype.scale = function (scale) {
  43167. this.l00 = this.l00.scale(scale);
  43168. this.l1_1 = this.l1_1.scale(scale);
  43169. this.l10 = this.l10.scale(scale);
  43170. this.l11 = this.l11.scale(scale);
  43171. this.l2_2 = this.l2_2.scale(scale);
  43172. this.l2_1 = this.l2_1.scale(scale);
  43173. this.l20 = this.l20.scale(scale);
  43174. this.l21 = this.l21.scale(scale);
  43175. this.lL22 = this.lL22.scale(scale);
  43176. };
  43177. /**
  43178. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43179. *
  43180. * ```
  43181. * E_lm = A_l * L_lm
  43182. * ```
  43183. *
  43184. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43185. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43186. * the scaling factors are given in equation 9.
  43187. */
  43188. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43189. // Constant (Band 0)
  43190. this.l00 = this.l00.scale(3.141593);
  43191. // Linear (Band 1)
  43192. this.l1_1 = this.l1_1.scale(2.094395);
  43193. this.l10 = this.l10.scale(2.094395);
  43194. this.l11 = this.l11.scale(2.094395);
  43195. // Quadratic (Band 2)
  43196. this.l2_2 = this.l2_2.scale(0.785398);
  43197. this.l2_1 = this.l2_1.scale(0.785398);
  43198. this.l20 = this.l20.scale(0.785398);
  43199. this.l21 = this.l21.scale(0.785398);
  43200. this.lL22 = this.lL22.scale(0.785398);
  43201. };
  43202. /**
  43203. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43204. *
  43205. * ```
  43206. * L = (1/pi) * E * rho
  43207. * ```
  43208. *
  43209. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43210. */
  43211. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43212. this.scale(1.0 / Math.PI);
  43213. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43214. // (The pixel shader must apply albedo after texture fetches, etc).
  43215. };
  43216. /**
  43217. * Gets the spherical harmonics from polynomial
  43218. * @param polynomial the spherical polynomial
  43219. * @returns the spherical harmonics
  43220. */
  43221. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43222. var result = new SphericalHarmonics();
  43223. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43224. result.l1_1 = polynomial.y.scale(0.977204);
  43225. result.l10 = polynomial.z.scale(0.977204);
  43226. result.l11 = polynomial.x.scale(0.977204);
  43227. result.l2_2 = polynomial.xy.scale(1.16538);
  43228. result.l2_1 = polynomial.yz.scale(1.16538);
  43229. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43230. result.l21 = polynomial.zx.scale(1.16538);
  43231. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43232. result.scale(Math.PI);
  43233. return result;
  43234. };
  43235. /**
  43236. * Constructs a spherical harmonics from an array.
  43237. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43238. * @returns the spherical harmonics
  43239. */
  43240. SphericalHarmonics.FromArray = function (data) {
  43241. var sh = new SphericalHarmonics();
  43242. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43243. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43244. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43245. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43246. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43247. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43248. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43249. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43250. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43251. return sh;
  43252. };
  43253. return SphericalHarmonics;
  43254. }());
  43255. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43256. })(BABYLON || (BABYLON = {}));
  43257. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43258. var BABYLON;
  43259. (function (BABYLON) {
  43260. var FileFaceOrientation = /** @class */ (function () {
  43261. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43262. this.name = name;
  43263. this.worldAxisForNormal = worldAxisForNormal;
  43264. this.worldAxisForFileX = worldAxisForFileX;
  43265. this.worldAxisForFileY = worldAxisForFileY;
  43266. }
  43267. return FileFaceOrientation;
  43268. }());
  43269. ;
  43270. /**
  43271. * Helper class dealing with the extraction of spherical polynomial dataArray
  43272. * from a cube map.
  43273. */
  43274. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43275. function CubeMapToSphericalPolynomialTools() {
  43276. }
  43277. /**
  43278. * Converts a texture to the according Spherical Polynomial data.
  43279. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43280. *
  43281. * @param texture The texture to extract the information from.
  43282. * @return The Spherical Polynomial data.
  43283. */
  43284. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43285. if (!texture.isCube) {
  43286. // Only supports cube Textures currently.
  43287. return null;
  43288. }
  43289. var size = texture.getSize().width;
  43290. var right = texture.readPixels(0);
  43291. var left = texture.readPixels(1);
  43292. var up;
  43293. var down;
  43294. if (texture.isRenderTarget) {
  43295. up = texture.readPixels(3);
  43296. down = texture.readPixels(2);
  43297. }
  43298. else {
  43299. up = texture.readPixels(2);
  43300. down = texture.readPixels(3);
  43301. }
  43302. var front = texture.readPixels(4);
  43303. var back = texture.readPixels(5);
  43304. var gammaSpace = texture.gammaSpace;
  43305. // Always read as RGBA.
  43306. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43307. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43308. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43309. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43310. }
  43311. var cubeInfo = {
  43312. size: size,
  43313. right: right,
  43314. left: left,
  43315. up: up,
  43316. down: down,
  43317. front: front,
  43318. back: back,
  43319. format: format,
  43320. type: type,
  43321. gammaSpace: gammaSpace,
  43322. };
  43323. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43324. };
  43325. /**
  43326. * Converts a cubemap to the according Spherical Polynomial data.
  43327. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43328. *
  43329. * @param cubeInfo The Cube map to extract the information from.
  43330. * @return The Spherical Polynomial data.
  43331. */
  43332. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43333. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43334. var totalSolidAngle = 0.0;
  43335. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43336. var du = 2.0 / cubeInfo.size;
  43337. var dv = du;
  43338. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43339. var minUV = du * 0.5 - 1.0;
  43340. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43341. var fileFace = this.FileFaces[faceIndex];
  43342. var dataArray = cubeInfo[fileFace.name];
  43343. var v = minUV;
  43344. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43345. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43346. // Because SP is still linear, so summation is fine in that basis.
  43347. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43348. for (var y = 0; y < cubeInfo.size; y++) {
  43349. var u = minUV;
  43350. for (var x = 0; x < cubeInfo.size; x++) {
  43351. // World direction (not normalised)
  43352. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43353. worldDirection.normalize();
  43354. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43355. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43356. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43357. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43358. // Handle Integer types.
  43359. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43360. r /= 255;
  43361. g /= 255;
  43362. b /= 255;
  43363. }
  43364. // Handle Gamma space textures.
  43365. if (cubeInfo.gammaSpace) {
  43366. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43367. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43368. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43369. }
  43370. var color = new BABYLON.Color3(r, g, b);
  43371. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43372. totalSolidAngle += deltaSolidAngle;
  43373. u += du;
  43374. }
  43375. v += dv;
  43376. }
  43377. }
  43378. // Solid angle for entire sphere is 4*pi
  43379. var sphereSolidAngle = 4.0 * Math.PI;
  43380. // Adjust the solid angle to allow for how many faces we processed.
  43381. var facesProcessed = 6.0;
  43382. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43383. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43384. // This is needed because the numerical integration over the cube uses a
  43385. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43386. // and also to compensate for accumulative error due to float precision in the summation.
  43387. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43388. sphericalHarmonics.scale(correctionFactor);
  43389. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43390. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43391. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43392. };
  43393. CubeMapToSphericalPolynomialTools.FileFaces = [
  43394. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43395. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43396. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43397. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43398. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43399. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43400. ];
  43401. return CubeMapToSphericalPolynomialTools;
  43402. }());
  43403. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43404. })(BABYLON || (BABYLON = {}));
  43405. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43406. var BABYLON;
  43407. (function (BABYLON) {
  43408. /**
  43409. * Manages the defines for the PBR Material.
  43410. * @hiddenChildren
  43411. */
  43412. var PBRMaterialDefines = /** @class */ (function (_super) {
  43413. __extends(PBRMaterialDefines, _super);
  43414. /**
  43415. * Initializes the PBR Material defines.
  43416. */
  43417. function PBRMaterialDefines() {
  43418. var _this = _super.call(this) || this;
  43419. _this.PBR = true;
  43420. _this.MAINUV1 = false;
  43421. _this.MAINUV2 = false;
  43422. _this.UV1 = false;
  43423. _this.UV2 = false;
  43424. _this.ALBEDO = false;
  43425. _this.ALBEDODIRECTUV = 0;
  43426. _this.VERTEXCOLOR = false;
  43427. _this.AMBIENT = false;
  43428. _this.AMBIENTDIRECTUV = 0;
  43429. _this.AMBIENTINGRAYSCALE = false;
  43430. _this.OPACITY = false;
  43431. _this.VERTEXALPHA = false;
  43432. _this.OPACITYDIRECTUV = 0;
  43433. _this.OPACITYRGB = false;
  43434. _this.ALPHATEST = false;
  43435. _this.DEPTHPREPASS = false;
  43436. _this.ALPHABLEND = false;
  43437. _this.ALPHAFROMALBEDO = false;
  43438. _this.ALPHATESTVALUE = "0.5";
  43439. _this.SPECULAROVERALPHA = false;
  43440. _this.RADIANCEOVERALPHA = false;
  43441. _this.ALPHAFRESNEL = false;
  43442. _this.LINEARALPHAFRESNEL = false;
  43443. _this.PREMULTIPLYALPHA = false;
  43444. _this.EMISSIVE = false;
  43445. _this.EMISSIVEDIRECTUV = 0;
  43446. _this.REFLECTIVITY = false;
  43447. _this.REFLECTIVITYDIRECTUV = 0;
  43448. _this.SPECULARTERM = false;
  43449. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43450. _this.MICROSURFACEAUTOMATIC = false;
  43451. _this.LODBASEDMICROSFURACE = false;
  43452. _this.MICROSURFACEMAP = false;
  43453. _this.MICROSURFACEMAPDIRECTUV = 0;
  43454. _this.METALLICWORKFLOW = false;
  43455. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43456. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43457. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43458. _this.AOSTOREINMETALMAPRED = false;
  43459. _this.ENVIRONMENTBRDF = false;
  43460. _this.NORMAL = false;
  43461. _this.TANGENT = false;
  43462. _this.BUMP = false;
  43463. _this.BUMPDIRECTUV = 0;
  43464. _this.OBJECTSPACE_NORMALMAP = false;
  43465. _this.PARALLAX = false;
  43466. _this.PARALLAXOCCLUSION = false;
  43467. _this.NORMALXYSCALE = true;
  43468. _this.LIGHTMAP = false;
  43469. _this.LIGHTMAPDIRECTUV = 0;
  43470. _this.USELIGHTMAPASSHADOWMAP = false;
  43471. _this.GAMMALIGHTMAP = false;
  43472. _this.REFLECTION = false;
  43473. _this.REFLECTIONMAP_3D = false;
  43474. _this.REFLECTIONMAP_SPHERICAL = false;
  43475. _this.REFLECTIONMAP_PLANAR = false;
  43476. _this.REFLECTIONMAP_CUBIC = false;
  43477. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43478. _this.REFLECTIONMAP_PROJECTION = false;
  43479. _this.REFLECTIONMAP_SKYBOX = false;
  43480. _this.REFLECTIONMAP_EXPLICIT = false;
  43481. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43482. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43483. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43484. _this.INVERTCUBICMAP = false;
  43485. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43486. _this.USESPHERICALINVERTEX = false;
  43487. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43488. _this.LODINREFLECTIONALPHA = false;
  43489. _this.GAMMAREFLECTION = false;
  43490. _this.RGBDREFLECTION = false;
  43491. _this.RADIANCEOCCLUSION = false;
  43492. _this.HORIZONOCCLUSION = false;
  43493. _this.REFRACTION = false;
  43494. _this.REFRACTIONMAP_3D = false;
  43495. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43496. _this.LODINREFRACTIONALPHA = false;
  43497. _this.GAMMAREFRACTION = false;
  43498. _this.RGBDREFRACTION = false;
  43499. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43500. _this.INSTANCES = false;
  43501. _this.NUM_BONE_INFLUENCERS = 0;
  43502. _this.BonesPerMesh = 0;
  43503. _this.NONUNIFORMSCALING = false;
  43504. _this.MORPHTARGETS = false;
  43505. _this.MORPHTARGETS_NORMAL = false;
  43506. _this.MORPHTARGETS_TANGENT = false;
  43507. _this.NUM_MORPH_INFLUENCERS = 0;
  43508. _this.IMAGEPROCESSING = false;
  43509. _this.VIGNETTE = false;
  43510. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43511. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43512. _this.TONEMAPPING = false;
  43513. _this.TONEMAPPING_ACES = false;
  43514. _this.CONTRAST = false;
  43515. _this.COLORCURVES = false;
  43516. _this.COLORGRADING = false;
  43517. _this.COLORGRADING3D = false;
  43518. _this.SAMPLER3DGREENDEPTH = false;
  43519. _this.SAMPLER3DBGRMAP = false;
  43520. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43521. _this.EXPOSURE = false;
  43522. _this.USEPHYSICALLIGHTFALLOFF = false;
  43523. _this.USEGLTFLIGHTFALLOFF = false;
  43524. _this.TWOSIDEDLIGHTING = false;
  43525. _this.SHADOWFLOAT = false;
  43526. _this.CLIPPLANE = false;
  43527. _this.POINTSIZE = false;
  43528. _this.FOG = false;
  43529. _this.LOGARITHMICDEPTH = false;
  43530. _this.FORCENORMALFORWARD = false;
  43531. _this.SPECULARAA = false;
  43532. _this.UNLIT = false;
  43533. _this.rebuild();
  43534. return _this;
  43535. }
  43536. /**
  43537. * Resets the PBR Material defines.
  43538. */
  43539. PBRMaterialDefines.prototype.reset = function () {
  43540. _super.prototype.reset.call(this);
  43541. this.ALPHATESTVALUE = "0.5";
  43542. this.PBR = true;
  43543. };
  43544. return PBRMaterialDefines;
  43545. }(BABYLON.MaterialDefines));
  43546. /**
  43547. * The Physically based material base class of BJS.
  43548. *
  43549. * This offers the main features of a standard PBR material.
  43550. * For more information, please refer to the documentation :
  43551. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43552. */
  43553. var PBRBaseMaterial = /** @class */ (function (_super) {
  43554. __extends(PBRBaseMaterial, _super);
  43555. /**
  43556. * Instantiates a new PBRMaterial instance.
  43557. *
  43558. * @param name The material name
  43559. * @param scene The scene the material will be use in.
  43560. */
  43561. function PBRBaseMaterial(name, scene) {
  43562. var _this = _super.call(this, name, scene) || this;
  43563. /**
  43564. * Intensity of the direct lights e.g. the four lights available in your scene.
  43565. * This impacts both the direct diffuse and specular highlights.
  43566. */
  43567. _this._directIntensity = 1.0;
  43568. /**
  43569. * Intensity of the emissive part of the material.
  43570. * This helps controlling the emissive effect without modifying the emissive color.
  43571. */
  43572. _this._emissiveIntensity = 1.0;
  43573. /**
  43574. * Intensity of the environment e.g. how much the environment will light the object
  43575. * either through harmonics for rough material or through the refelction for shiny ones.
  43576. */
  43577. _this._environmentIntensity = 1.0;
  43578. /**
  43579. * This is a special control allowing the reduction of the specular highlights coming from the
  43580. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43581. */
  43582. _this._specularIntensity = 1.0;
  43583. /**
  43584. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43585. */
  43586. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43587. /**
  43588. * Debug Control allowing disabling the bump map on this material.
  43589. */
  43590. _this._disableBumpMap = false;
  43591. /**
  43592. * AKA Occlusion Texture Intensity in other nomenclature.
  43593. */
  43594. _this._ambientTextureStrength = 1.0;
  43595. /**
  43596. * The color of a material in ambient lighting.
  43597. */
  43598. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43599. /**
  43600. * AKA Diffuse Color in other nomenclature.
  43601. */
  43602. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43603. /**
  43604. * AKA Specular Color in other nomenclature.
  43605. */
  43606. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43607. /**
  43608. * The color applied when light is reflected from a material.
  43609. */
  43610. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43611. /**
  43612. * The color applied when light is emitted from a material.
  43613. */
  43614. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43615. /**
  43616. * AKA Glossiness in other nomenclature.
  43617. */
  43618. _this._microSurface = 0.9;
  43619. /**
  43620. * source material index of refraction (IOR)' / 'destination material IOR.
  43621. */
  43622. _this._indexOfRefraction = 0.66;
  43623. /**
  43624. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43625. */
  43626. _this._invertRefractionY = false;
  43627. /**
  43628. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43629. * Materials half opaque for instance using refraction could benefit from this control.
  43630. */
  43631. _this._linkRefractionWithTransparency = false;
  43632. /**
  43633. * Specifies that the material will use the light map as a show map.
  43634. */
  43635. _this._useLightmapAsShadowmap = false;
  43636. /**
  43637. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43638. * makes the reflect vector face the model (under horizon).
  43639. */
  43640. _this._useHorizonOcclusion = true;
  43641. /**
  43642. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43643. * too much the area relying on ambient texture to define their ambient occlusion.
  43644. */
  43645. _this._useRadianceOcclusion = true;
  43646. /**
  43647. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43648. */
  43649. _this._useAlphaFromAlbedoTexture = false;
  43650. /**
  43651. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43652. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43653. */
  43654. _this._useSpecularOverAlpha = true;
  43655. /**
  43656. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43657. */
  43658. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43659. /**
  43660. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43661. */
  43662. _this._useRoughnessFromMetallicTextureAlpha = true;
  43663. /**
  43664. * Specifies if the metallic texture contains the roughness information in its green channel.
  43665. */
  43666. _this._useRoughnessFromMetallicTextureGreen = false;
  43667. /**
  43668. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43669. */
  43670. _this._useMetallnessFromMetallicTextureBlue = false;
  43671. /**
  43672. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43673. */
  43674. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43675. /**
  43676. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43677. */
  43678. _this._useAmbientInGrayScale = false;
  43679. /**
  43680. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43681. * The material will try to infer what glossiness each pixel should be.
  43682. */
  43683. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43684. /**
  43685. * Defines the falloff type used in this material.
  43686. * It by default is Physical.
  43687. */
  43688. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43689. /**
  43690. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43691. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43692. */
  43693. _this._useRadianceOverAlpha = true;
  43694. /**
  43695. * Allows using an object space normal map (instead of tangent space).
  43696. */
  43697. _this._useObjectSpaceNormalMap = false;
  43698. /**
  43699. * Allows using the bump map in parallax mode.
  43700. */
  43701. _this._useParallax = false;
  43702. /**
  43703. * Allows using the bump map in parallax occlusion mode.
  43704. */
  43705. _this._useParallaxOcclusion = false;
  43706. /**
  43707. * Controls the scale bias of the parallax mode.
  43708. */
  43709. _this._parallaxScaleBias = 0.05;
  43710. /**
  43711. * If sets to true, disables all the lights affecting the material.
  43712. */
  43713. _this._disableLighting = false;
  43714. /**
  43715. * Number of Simultaneous lights allowed on the material.
  43716. */
  43717. _this._maxSimultaneousLights = 4;
  43718. /**
  43719. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43720. */
  43721. _this._invertNormalMapX = false;
  43722. /**
  43723. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43724. */
  43725. _this._invertNormalMapY = false;
  43726. /**
  43727. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43728. */
  43729. _this._twoSidedLighting = false;
  43730. /**
  43731. * Defines the alpha limits in alpha test mode.
  43732. */
  43733. _this._alphaCutOff = 0.4;
  43734. /**
  43735. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43736. */
  43737. _this._forceAlphaTest = false;
  43738. /**
  43739. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43740. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43741. */
  43742. _this._useAlphaFresnel = false;
  43743. /**
  43744. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43745. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43746. */
  43747. _this._useLinearAlphaFresnel = false;
  43748. /**
  43749. * The transparency mode of the material.
  43750. */
  43751. _this._transparencyMode = null;
  43752. /**
  43753. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43754. * from cos thetav and roughness:
  43755. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43756. */
  43757. _this._environmentBRDFTexture = null;
  43758. /**
  43759. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43760. */
  43761. _this._forceIrradianceInFragment = false;
  43762. /**
  43763. * Force normal to face away from face.
  43764. */
  43765. _this._forceNormalForward = false;
  43766. /**
  43767. * Enables specular anti aliasing in the PBR shader.
  43768. * It will both interacts on the Geometry for analytical and IBL lighting.
  43769. * It also prefilter the roughness map based on the bump values.
  43770. */
  43771. _this._enableSpecularAntiAliasing = false;
  43772. /**
  43773. * Stores the available render targets.
  43774. */
  43775. _this._renderTargets = new BABYLON.SmartArray(16);
  43776. /**
  43777. * Sets the global ambient color for the material used in lighting calculations.
  43778. */
  43779. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43780. /**
  43781. * If set to true, no lighting calculations will be applied.
  43782. */
  43783. _this._unlit = false;
  43784. // Setup the default processing configuration to the scene.
  43785. _this._attachImageProcessingConfiguration(null);
  43786. _this.getRenderTargetTextures = function () {
  43787. _this._renderTargets.reset();
  43788. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43789. _this._renderTargets.push(_this._reflectionTexture);
  43790. }
  43791. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43792. _this._renderTargets.push(_this._refractionTexture);
  43793. }
  43794. return _this._renderTargets;
  43795. };
  43796. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43797. return _this;
  43798. }
  43799. /**
  43800. * Attaches a new image processing configuration to the PBR Material.
  43801. * @param configuration
  43802. */
  43803. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43804. var _this = this;
  43805. if (configuration === this._imageProcessingConfiguration) {
  43806. return;
  43807. }
  43808. // Detaches observer.
  43809. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43810. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43811. }
  43812. // Pick the scene configuration if needed.
  43813. if (!configuration) {
  43814. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43815. }
  43816. else {
  43817. this._imageProcessingConfiguration = configuration;
  43818. }
  43819. // Attaches observer.
  43820. if (this._imageProcessingConfiguration) {
  43821. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43822. _this._markAllSubMeshesAsImageProcessingDirty();
  43823. });
  43824. }
  43825. };
  43826. /**
  43827. * Gets the name of the material class.
  43828. */
  43829. PBRBaseMaterial.prototype.getClassName = function () {
  43830. return "PBRBaseMaterial";
  43831. };
  43832. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43833. /**
  43834. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43835. */
  43836. get: function () {
  43837. return this._useLogarithmicDepth;
  43838. },
  43839. /**
  43840. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43841. */
  43842. set: function (value) {
  43843. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43844. },
  43845. enumerable: true,
  43846. configurable: true
  43847. });
  43848. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43849. /**
  43850. * Gets the current transparency mode.
  43851. */
  43852. get: function () {
  43853. return this._transparencyMode;
  43854. },
  43855. /**
  43856. * Sets the transparency mode of the material.
  43857. *
  43858. * | Value | Type | Description |
  43859. * | ----- | ----------------------------------- | ----------- |
  43860. * | 0 | OPAQUE | |
  43861. * | 1 | ALPHATEST | |
  43862. * | 2 | ALPHABLEND | |
  43863. * | 3 | ALPHATESTANDBLEND | |
  43864. *
  43865. */
  43866. set: function (value) {
  43867. if (this._transparencyMode === value) {
  43868. return;
  43869. }
  43870. this._transparencyMode = value;
  43871. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43872. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43873. },
  43874. enumerable: true,
  43875. configurable: true
  43876. });
  43877. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43878. /**
  43879. * Returns true if alpha blending should be disabled.
  43880. */
  43881. get: function () {
  43882. return (this._linkRefractionWithTransparency ||
  43883. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43884. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43885. },
  43886. enumerable: true,
  43887. configurable: true
  43888. });
  43889. /**
  43890. * Specifies whether or not this material should be rendered in alpha blend mode.
  43891. */
  43892. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43893. if (this._disableAlphaBlending) {
  43894. return false;
  43895. }
  43896. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43897. };
  43898. /**
  43899. * Specifies if the mesh will require alpha blending.
  43900. * @param mesh - BJS mesh.
  43901. */
  43902. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43903. if (this._disableAlphaBlending) {
  43904. return false;
  43905. }
  43906. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43907. };
  43908. /**
  43909. * Specifies whether or not this material should be rendered in alpha test mode.
  43910. */
  43911. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43912. if (this._forceAlphaTest) {
  43913. return true;
  43914. }
  43915. if (this._linkRefractionWithTransparency) {
  43916. return false;
  43917. }
  43918. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43919. };
  43920. /**
  43921. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43922. */
  43923. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43924. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43925. };
  43926. /**
  43927. * Gets the texture used for the alpha test.
  43928. */
  43929. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43930. return this._albedoTexture;
  43931. };
  43932. /**
  43933. * Specifies that the submesh is ready to be used.
  43934. * @param mesh - BJS mesh.
  43935. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43936. * @param useInstances - Specifies that instances should be used.
  43937. * @returns - boolean indicating that the submesh is ready or not.
  43938. */
  43939. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43940. if (subMesh.effect && this.isFrozen) {
  43941. if (this._wasPreviouslyReady) {
  43942. return true;
  43943. }
  43944. }
  43945. if (!subMesh._materialDefines) {
  43946. subMesh._materialDefines = new PBRMaterialDefines();
  43947. }
  43948. var defines = subMesh._materialDefines;
  43949. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43950. if (defines._renderId === this.getScene().getRenderId()) {
  43951. return true;
  43952. }
  43953. }
  43954. var scene = this.getScene();
  43955. var engine = scene.getEngine();
  43956. if (defines._areTexturesDirty) {
  43957. if (scene.texturesEnabled) {
  43958. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43959. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43960. return false;
  43961. }
  43962. }
  43963. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43964. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43965. return false;
  43966. }
  43967. }
  43968. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43969. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43970. return false;
  43971. }
  43972. }
  43973. var reflectionTexture = this._getReflectionTexture();
  43974. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43975. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43976. return false;
  43977. }
  43978. }
  43979. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43980. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43981. return false;
  43982. }
  43983. }
  43984. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43985. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43986. return false;
  43987. }
  43988. }
  43989. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43990. if (this._metallicTexture) {
  43991. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43992. return false;
  43993. }
  43994. }
  43995. else if (this._reflectivityTexture) {
  43996. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43997. return false;
  43998. }
  43999. }
  44000. if (this._microSurfaceTexture) {
  44001. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44002. return false;
  44003. }
  44004. }
  44005. }
  44006. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44007. // Bump texture cannot be not blocking.
  44008. if (!this._bumpTexture.isReady()) {
  44009. return false;
  44010. }
  44011. }
  44012. var refractionTexture = this._getRefractionTexture();
  44013. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44014. if (!refractionTexture.isReadyOrNotBlocking()) {
  44015. return false;
  44016. }
  44017. }
  44018. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44019. // This is blocking.
  44020. if (!this._environmentBRDFTexture.isReady()) {
  44021. return false;
  44022. }
  44023. }
  44024. }
  44025. }
  44026. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44027. if (!this._imageProcessingConfiguration.isReady()) {
  44028. return false;
  44029. }
  44030. }
  44031. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44032. mesh.createNormals(true);
  44033. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44034. }
  44035. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44036. if (effect) {
  44037. scene.resetCachedMaterial();
  44038. subMesh.setEffect(effect, defines);
  44039. this.buildUniformLayout();
  44040. }
  44041. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44042. return false;
  44043. }
  44044. defines._renderId = scene.getRenderId();
  44045. this._wasPreviouslyReady = true;
  44046. return true;
  44047. };
  44048. /**
  44049. * Specifies if the material uses metallic roughness workflow.
  44050. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44051. */
  44052. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44053. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44054. return true;
  44055. }
  44056. return false;
  44057. };
  44058. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44059. if (onCompiled === void 0) { onCompiled = null; }
  44060. if (onError === void 0) { onError = null; }
  44061. if (useInstances === void 0) { useInstances = null; }
  44062. if (useClipPlane === void 0) { useClipPlane = null; }
  44063. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44064. if (!defines.isDirty) {
  44065. return null;
  44066. }
  44067. defines.markAsProcessed();
  44068. var scene = this.getScene();
  44069. var engine = scene.getEngine();
  44070. // Fallbacks
  44071. var fallbacks = new BABYLON.EffectFallbacks();
  44072. var fallbackRank = 0;
  44073. if (defines.USESPHERICALINVERTEX) {
  44074. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44075. }
  44076. if (defines.FOG) {
  44077. fallbacks.addFallback(fallbackRank, "FOG");
  44078. }
  44079. if (defines.SPECULARAA) {
  44080. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44081. }
  44082. if (defines.POINTSIZE) {
  44083. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44084. }
  44085. if (defines.LOGARITHMICDEPTH) {
  44086. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44087. }
  44088. if (defines.PARALLAX) {
  44089. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44090. }
  44091. if (defines.PARALLAXOCCLUSION) {
  44092. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44093. }
  44094. if (defines.ENVIRONMENTBRDF) {
  44095. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44096. }
  44097. if (defines.TANGENT) {
  44098. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44099. }
  44100. if (defines.BUMP) {
  44101. fallbacks.addFallback(fallbackRank++, "BUMP");
  44102. }
  44103. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44104. if (defines.SPECULARTERM) {
  44105. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44106. }
  44107. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44108. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44109. }
  44110. if (defines.LIGHTMAP) {
  44111. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44112. }
  44113. if (defines.NORMAL) {
  44114. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44115. }
  44116. if (defines.AMBIENT) {
  44117. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44118. }
  44119. if (defines.EMISSIVE) {
  44120. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44121. }
  44122. if (defines.VERTEXCOLOR) {
  44123. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44124. }
  44125. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44126. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44127. }
  44128. if (defines.MORPHTARGETS) {
  44129. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44130. }
  44131. //Attributes
  44132. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44133. if (defines.NORMAL) {
  44134. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44135. }
  44136. if (defines.TANGENT) {
  44137. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44138. }
  44139. if (defines.UV1) {
  44140. attribs.push(BABYLON.VertexBuffer.UVKind);
  44141. }
  44142. if (defines.UV2) {
  44143. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44144. }
  44145. if (defines.VERTEXCOLOR) {
  44146. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44147. }
  44148. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44149. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44150. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44151. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44152. "vFogInfos", "vFogColor", "pointSize",
  44153. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44154. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44155. "mBones",
  44156. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44157. "vLightingIntensity",
  44158. "logarithmicDepthConstant",
  44159. "vSphericalX", "vSphericalY", "vSphericalZ",
  44160. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44161. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44162. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44163. "vTangentSpaceParams"
  44164. ];
  44165. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44166. "bumpSampler", "lightmapSampler", "opacitySampler",
  44167. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44168. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44169. "microSurfaceSampler", "environmentBrdfSampler"];
  44170. var uniformBuffers = ["Material", "Scene"];
  44171. if (BABYLON.ImageProcessingConfiguration) {
  44172. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44173. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44174. }
  44175. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44176. uniformsNames: uniforms,
  44177. uniformBuffersNames: uniformBuffers,
  44178. samplers: samplers,
  44179. defines: defines,
  44180. maxSimultaneousLights: this._maxSimultaneousLights
  44181. });
  44182. var join = defines.toString();
  44183. return engine.createEffect("pbr", {
  44184. attributes: attribs,
  44185. uniformsNames: uniforms,
  44186. uniformBuffersNames: uniformBuffers,
  44187. samplers: samplers,
  44188. defines: join,
  44189. fallbacks: fallbacks,
  44190. onCompiled: onCompiled,
  44191. onError: onError,
  44192. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44193. }, engine);
  44194. };
  44195. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44196. if (useInstances === void 0) { useInstances = null; }
  44197. if (useClipPlane === void 0) { useClipPlane = null; }
  44198. var scene = this.getScene();
  44199. var engine = scene.getEngine();
  44200. // Lights
  44201. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44202. defines._needNormals = true;
  44203. // Textures
  44204. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44205. if (defines._areTexturesDirty) {
  44206. defines._needUVs = false;
  44207. if (scene.texturesEnabled) {
  44208. if (scene.getEngine().getCaps().textureLOD) {
  44209. defines.LODBASEDMICROSFURACE = true;
  44210. }
  44211. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44212. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44213. }
  44214. else {
  44215. defines.ALBEDO = false;
  44216. }
  44217. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44218. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44219. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44220. }
  44221. else {
  44222. defines.AMBIENT = false;
  44223. }
  44224. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44225. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44226. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44227. }
  44228. else {
  44229. defines.OPACITY = false;
  44230. }
  44231. var reflectionTexture = this._getReflectionTexture();
  44232. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44233. defines.REFLECTION = true;
  44234. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44235. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44236. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44237. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44238. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44239. defines.INVERTCUBICMAP = true;
  44240. }
  44241. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44242. switch (reflectionTexture.coordinatesMode) {
  44243. case BABYLON.Texture.EXPLICIT_MODE:
  44244. defines.REFLECTIONMAP_EXPLICIT = true;
  44245. break;
  44246. case BABYLON.Texture.PLANAR_MODE:
  44247. defines.REFLECTIONMAP_PLANAR = true;
  44248. break;
  44249. case BABYLON.Texture.PROJECTION_MODE:
  44250. defines.REFLECTIONMAP_PROJECTION = true;
  44251. break;
  44252. case BABYLON.Texture.SKYBOX_MODE:
  44253. defines.REFLECTIONMAP_SKYBOX = true;
  44254. break;
  44255. case BABYLON.Texture.SPHERICAL_MODE:
  44256. defines.REFLECTIONMAP_SPHERICAL = true;
  44257. break;
  44258. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44259. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44260. break;
  44261. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44262. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44263. break;
  44264. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44265. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44266. break;
  44267. case BABYLON.Texture.CUBIC_MODE:
  44268. case BABYLON.Texture.INVCUBIC_MODE:
  44269. default:
  44270. defines.REFLECTIONMAP_CUBIC = true;
  44271. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44272. break;
  44273. }
  44274. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44275. if (reflectionTexture.sphericalPolynomial) {
  44276. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44277. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44278. defines.USESPHERICALINVERTEX = false;
  44279. }
  44280. else {
  44281. defines.USESPHERICALINVERTEX = true;
  44282. }
  44283. }
  44284. }
  44285. }
  44286. else {
  44287. defines.REFLECTION = false;
  44288. defines.REFLECTIONMAP_3D = false;
  44289. defines.REFLECTIONMAP_SPHERICAL = false;
  44290. defines.REFLECTIONMAP_PLANAR = false;
  44291. defines.REFLECTIONMAP_CUBIC = false;
  44292. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44293. defines.REFLECTIONMAP_PROJECTION = false;
  44294. defines.REFLECTIONMAP_SKYBOX = false;
  44295. defines.REFLECTIONMAP_EXPLICIT = false;
  44296. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44297. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44298. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44299. defines.INVERTCUBICMAP = false;
  44300. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44301. defines.USESPHERICALINVERTEX = false;
  44302. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44303. defines.LODINREFLECTIONALPHA = false;
  44304. defines.GAMMAREFLECTION = false;
  44305. defines.RGBDREFLECTION = false;
  44306. }
  44307. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44308. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44309. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44310. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44311. }
  44312. else {
  44313. defines.LIGHTMAP = false;
  44314. }
  44315. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44316. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44317. }
  44318. else {
  44319. defines.EMISSIVE = false;
  44320. }
  44321. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44322. if (this._metallicTexture) {
  44323. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44324. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44325. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44326. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44327. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44328. }
  44329. else if (this._reflectivityTexture) {
  44330. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44331. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44332. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44333. }
  44334. else {
  44335. defines.REFLECTIVITY = false;
  44336. }
  44337. if (this._microSurfaceTexture) {
  44338. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44339. }
  44340. else {
  44341. defines.MICROSURFACEMAP = false;
  44342. }
  44343. }
  44344. else {
  44345. defines.REFLECTIVITY = false;
  44346. defines.MICROSURFACEMAP = false;
  44347. }
  44348. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44349. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44350. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44351. defines.PARALLAX = true;
  44352. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44353. }
  44354. else {
  44355. defines.PARALLAX = false;
  44356. }
  44357. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44358. }
  44359. else {
  44360. defines.BUMP = false;
  44361. }
  44362. var refractionTexture = this._getRefractionTexture();
  44363. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44364. defines.REFRACTION = true;
  44365. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44366. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44367. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44368. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44369. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44370. if (this._linkRefractionWithTransparency) {
  44371. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44372. }
  44373. }
  44374. else {
  44375. defines.REFRACTION = false;
  44376. }
  44377. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44378. defines.ENVIRONMENTBRDF = true;
  44379. }
  44380. else {
  44381. defines.ENVIRONMENTBRDF = false;
  44382. }
  44383. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44384. defines.ALPHAFROMALBEDO = true;
  44385. }
  44386. else {
  44387. defines.ALPHAFROMALBEDO = false;
  44388. }
  44389. }
  44390. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44391. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44392. defines.USEPHYSICALLIGHTFALLOFF = false;
  44393. defines.USEGLTFLIGHTFALLOFF = false;
  44394. }
  44395. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44396. defines.USEPHYSICALLIGHTFALLOFF = false;
  44397. defines.USEGLTFLIGHTFALLOFF = true;
  44398. }
  44399. else {
  44400. defines.USEPHYSICALLIGHTFALLOFF = true;
  44401. defines.USEGLTFLIGHTFALLOFF = false;
  44402. }
  44403. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44404. if (!this.backFaceCulling && this._twoSidedLighting) {
  44405. defines.TWOSIDEDLIGHTING = true;
  44406. }
  44407. else {
  44408. defines.TWOSIDEDLIGHTING = false;
  44409. }
  44410. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44411. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44412. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44413. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44414. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44415. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44416. }
  44417. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44418. this._imageProcessingConfiguration.prepareDefines(defines);
  44419. }
  44420. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44421. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44422. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44423. // Misc.
  44424. if (defines._areMiscDirty) {
  44425. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44426. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44427. }
  44428. // Values that need to be evaluated on every frame
  44429. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44430. // Attribs
  44431. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44432. };
  44433. /**
  44434. * Force shader compilation
  44435. */
  44436. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44437. var _this = this;
  44438. var localOptions = __assign({ clipPlane: false }, options);
  44439. var defines = new PBRMaterialDefines();
  44440. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44441. if (effect.isReady()) {
  44442. if (onCompiled) {
  44443. onCompiled(this);
  44444. }
  44445. }
  44446. else {
  44447. effect.onCompileObservable.add(function () {
  44448. if (onCompiled) {
  44449. onCompiled(_this);
  44450. }
  44451. });
  44452. }
  44453. };
  44454. /**
  44455. * Initializes the uniform buffer layout for the shader.
  44456. */
  44457. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44458. // Order is important !
  44459. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44460. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44461. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44462. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44463. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44464. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44465. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44466. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44467. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44468. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44469. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44470. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44471. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44472. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44473. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44474. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44475. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44476. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44477. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44478. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44479. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44480. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44481. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44482. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44483. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44484. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44485. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44486. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44487. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44488. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44489. this._uniformBuffer.addUniform("pointSize", 1);
  44490. this._uniformBuffer.create();
  44491. };
  44492. /**
  44493. * Unbinds the textures.
  44494. */
  44495. PBRBaseMaterial.prototype.unbind = function () {
  44496. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44497. this._uniformBuffer.setTexture("reflectionSampler", null);
  44498. }
  44499. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44500. this._uniformBuffer.setTexture("refractionSampler", null);
  44501. }
  44502. _super.prototype.unbind.call(this);
  44503. };
  44504. /**
  44505. * Binds the submesh data.
  44506. * @param world - The world matrix.
  44507. * @param mesh - The BJS mesh.
  44508. * @param subMesh - A submesh of the BJS mesh.
  44509. */
  44510. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44511. var scene = this.getScene();
  44512. var defines = subMesh._materialDefines;
  44513. if (!defines) {
  44514. return;
  44515. }
  44516. var effect = subMesh.effect;
  44517. if (!effect) {
  44518. return;
  44519. }
  44520. this._activeEffect = effect;
  44521. // Matrices
  44522. this.bindOnlyWorldMatrix(world);
  44523. // Normal Matrix
  44524. if (defines.OBJECTSPACE_NORMALMAP) {
  44525. world.toNormalMatrix(this._normalMatrix);
  44526. this.bindOnlyNormalMatrix(this._normalMatrix);
  44527. }
  44528. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44529. // Bones
  44530. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44531. var reflectionTexture = null;
  44532. if (mustRebind) {
  44533. this._uniformBuffer.bindToEffect(effect, "Material");
  44534. this.bindViewProjection(effect);
  44535. reflectionTexture = this._getReflectionTexture();
  44536. var refractionTexture = this._getRefractionTexture();
  44537. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44538. // Texture uniforms
  44539. if (scene.texturesEnabled) {
  44540. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44541. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44542. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44543. }
  44544. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44545. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44546. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44547. }
  44548. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44549. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44550. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44551. }
  44552. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44553. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44554. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44555. if (reflectionTexture.boundingBoxSize) {
  44556. var cubeTexture = reflectionTexture;
  44557. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44558. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44559. }
  44560. var polynomials = reflectionTexture.sphericalPolynomial;
  44561. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44562. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44563. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44564. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44565. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44566. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44567. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44568. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44569. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44570. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44571. }
  44572. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44573. }
  44574. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44575. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44576. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44577. }
  44578. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44579. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44580. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44581. }
  44582. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44583. if (this._metallicTexture) {
  44584. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44585. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44586. }
  44587. else if (this._reflectivityTexture) {
  44588. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44589. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44590. }
  44591. if (this._microSurfaceTexture) {
  44592. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44593. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44594. }
  44595. }
  44596. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44597. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44598. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44599. if (scene._mirroredCameraPosition) {
  44600. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44601. }
  44602. else {
  44603. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44604. }
  44605. }
  44606. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44607. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44608. var depth = 1.0;
  44609. if (!refractionTexture.isCube) {
  44610. if (refractionTexture.depth) {
  44611. depth = refractionTexture.depth;
  44612. }
  44613. }
  44614. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44615. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44616. }
  44617. }
  44618. // Point size
  44619. if (this.pointsCloud) {
  44620. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44621. }
  44622. // Colors
  44623. if (defines.METALLICWORKFLOW) {
  44624. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44625. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44626. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44627. }
  44628. else {
  44629. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44630. }
  44631. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44632. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44633. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44634. // Misc
  44635. this._lightingInfos.x = this._directIntensity;
  44636. this._lightingInfos.y = this._emissiveIntensity;
  44637. this._lightingInfos.z = this._environmentIntensity;
  44638. this._lightingInfos.w = this._specularIntensity;
  44639. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44640. }
  44641. // Textures
  44642. if (scene.texturesEnabled) {
  44643. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44644. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44645. }
  44646. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44647. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44648. }
  44649. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44650. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44651. }
  44652. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44653. if (defines.LODBASEDMICROSFURACE) {
  44654. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44655. }
  44656. else {
  44657. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44658. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44659. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44660. }
  44661. }
  44662. if (defines.ENVIRONMENTBRDF) {
  44663. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44664. }
  44665. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44666. if (defines.LODBASEDMICROSFURACE) {
  44667. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44668. }
  44669. else {
  44670. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44671. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44672. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44673. }
  44674. }
  44675. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44676. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44677. }
  44678. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44679. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44680. }
  44681. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44682. if (this._metallicTexture) {
  44683. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44684. }
  44685. else if (this._reflectivityTexture) {
  44686. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44687. }
  44688. if (this._microSurfaceTexture) {
  44689. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44690. }
  44691. }
  44692. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44693. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44694. }
  44695. }
  44696. // Clip plane
  44697. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44698. // Colors
  44699. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44700. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44701. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44702. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44703. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44704. }
  44705. if (mustRebind || !this.isFrozen) {
  44706. // Lights
  44707. if (scene.lightsEnabled && !this._disableLighting) {
  44708. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44709. }
  44710. // View
  44711. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44712. this.bindView(effect);
  44713. }
  44714. // Fog
  44715. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44716. // Morph targets
  44717. if (defines.NUM_MORPH_INFLUENCERS) {
  44718. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44719. }
  44720. // image processing
  44721. this._imageProcessingConfiguration.bind(this._activeEffect);
  44722. // Log. depth
  44723. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44724. }
  44725. this._uniformBuffer.update();
  44726. this._afterBind(mesh, this._activeEffect);
  44727. };
  44728. /**
  44729. * Returns the animatable textures.
  44730. * @returns - Array of animatable textures.
  44731. */
  44732. PBRBaseMaterial.prototype.getAnimatables = function () {
  44733. var results = [];
  44734. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44735. results.push(this._albedoTexture);
  44736. }
  44737. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44738. results.push(this._ambientTexture);
  44739. }
  44740. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44741. results.push(this._opacityTexture);
  44742. }
  44743. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44744. results.push(this._reflectionTexture);
  44745. }
  44746. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44747. results.push(this._emissiveTexture);
  44748. }
  44749. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44750. results.push(this._metallicTexture);
  44751. }
  44752. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44753. results.push(this._reflectivityTexture);
  44754. }
  44755. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44756. results.push(this._bumpTexture);
  44757. }
  44758. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44759. results.push(this._lightmapTexture);
  44760. }
  44761. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44762. results.push(this._refractionTexture);
  44763. }
  44764. return results;
  44765. };
  44766. /**
  44767. * Returns the texture used for reflections.
  44768. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44769. */
  44770. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44771. if (this._reflectionTexture) {
  44772. return this._reflectionTexture;
  44773. }
  44774. return this.getScene().environmentTexture;
  44775. };
  44776. /**
  44777. * Returns the texture used for refraction or null if none is used.
  44778. * @returns - Refection texture if present. If no refraction texture and refraction
  44779. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44780. */
  44781. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44782. if (this._refractionTexture) {
  44783. return this._refractionTexture;
  44784. }
  44785. if (this._linkRefractionWithTransparency) {
  44786. return this.getScene().environmentTexture;
  44787. }
  44788. return null;
  44789. };
  44790. /**
  44791. * Disposes the resources of the material.
  44792. * @param forceDisposeEffect - Forces the disposal of effects.
  44793. * @param forceDisposeTextures - Forces the disposal of all textures.
  44794. */
  44795. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44796. if (forceDisposeTextures) {
  44797. if (this._albedoTexture) {
  44798. this._albedoTexture.dispose();
  44799. }
  44800. if (this._ambientTexture) {
  44801. this._ambientTexture.dispose();
  44802. }
  44803. if (this._opacityTexture) {
  44804. this._opacityTexture.dispose();
  44805. }
  44806. if (this._reflectionTexture) {
  44807. this._reflectionTexture.dispose();
  44808. }
  44809. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44810. this._environmentBRDFTexture.dispose();
  44811. }
  44812. if (this._emissiveTexture) {
  44813. this._emissiveTexture.dispose();
  44814. }
  44815. if (this._metallicTexture) {
  44816. this._metallicTexture.dispose();
  44817. }
  44818. if (this._reflectivityTexture) {
  44819. this._reflectivityTexture.dispose();
  44820. }
  44821. if (this._bumpTexture) {
  44822. this._bumpTexture.dispose();
  44823. }
  44824. if (this._lightmapTexture) {
  44825. this._lightmapTexture.dispose();
  44826. }
  44827. if (this._refractionTexture) {
  44828. this._refractionTexture.dispose();
  44829. }
  44830. }
  44831. this._renderTargets.dispose();
  44832. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44833. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44834. }
  44835. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44836. };
  44837. /**
  44838. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44839. */
  44840. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44841. /**
  44842. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44843. * to enhance interoperability with other engines.
  44844. */
  44845. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44846. /**
  44847. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44848. * to enhance interoperability with other materials.
  44849. */
  44850. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44851. /**
  44852. * Stores the reflectivity values based on metallic roughness workflow.
  44853. */
  44854. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44855. __decorate([
  44856. BABYLON.serializeAsImageProcessingConfiguration()
  44857. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44858. __decorate([
  44859. BABYLON.serialize()
  44860. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44861. __decorate([
  44862. BABYLON.serialize()
  44863. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44864. return PBRBaseMaterial;
  44865. }(BABYLON.PushMaterial));
  44866. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44867. })(BABYLON || (BABYLON = {}));
  44868. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44869. var BABYLON;
  44870. (function (BABYLON) {
  44871. /**
  44872. * The Physically based simple base material of BJS.
  44873. *
  44874. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44875. * It is used as the base class for both the specGloss and metalRough conventions.
  44876. */
  44877. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44878. __extends(PBRBaseSimpleMaterial, _super);
  44879. /**
  44880. * Instantiates a new PBRMaterial instance.
  44881. *
  44882. * @param name The material name
  44883. * @param scene The scene the material will be use in.
  44884. */
  44885. function PBRBaseSimpleMaterial(name, scene) {
  44886. var _this = _super.call(this, name, scene) || this;
  44887. /**
  44888. * Number of Simultaneous lights allowed on the material.
  44889. */
  44890. _this.maxSimultaneousLights = 4;
  44891. /**
  44892. * If sets to true, disables all the lights affecting the material.
  44893. */
  44894. _this.disableLighting = false;
  44895. /**
  44896. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44897. */
  44898. _this.invertNormalMapX = false;
  44899. /**
  44900. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44901. */
  44902. _this.invertNormalMapY = false;
  44903. /**
  44904. * Emissivie color used to self-illuminate the model.
  44905. */
  44906. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44907. /**
  44908. * Occlusion Channel Strenght.
  44909. */
  44910. _this.occlusionStrength = 1.0;
  44911. _this.useLightmapAsShadowmap = false;
  44912. _this._useAlphaFromAlbedoTexture = true;
  44913. _this._useAmbientInGrayScale = true;
  44914. return _this;
  44915. }
  44916. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44917. /**
  44918. * Gets the current double sided mode.
  44919. */
  44920. get: function () {
  44921. return this._twoSidedLighting;
  44922. },
  44923. /**
  44924. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44925. */
  44926. set: function (value) {
  44927. if (this._twoSidedLighting === value) {
  44928. return;
  44929. }
  44930. this._twoSidedLighting = value;
  44931. this.backFaceCulling = !value;
  44932. this._markAllSubMeshesAsTexturesDirty();
  44933. },
  44934. enumerable: true,
  44935. configurable: true
  44936. });
  44937. /**
  44938. * Return the active textures of the material.
  44939. */
  44940. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44941. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44942. if (this.environmentTexture) {
  44943. activeTextures.push(this.environmentTexture);
  44944. }
  44945. if (this.normalTexture) {
  44946. activeTextures.push(this.normalTexture);
  44947. }
  44948. if (this.emissiveTexture) {
  44949. activeTextures.push(this.emissiveTexture);
  44950. }
  44951. if (this.occlusionTexture) {
  44952. activeTextures.push(this.occlusionTexture);
  44953. }
  44954. if (this.lightmapTexture) {
  44955. activeTextures.push(this.lightmapTexture);
  44956. }
  44957. return activeTextures;
  44958. };
  44959. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44960. if (_super.prototype.hasTexture.call(this, texture)) {
  44961. return true;
  44962. }
  44963. if (this.lightmapTexture === texture) {
  44964. return true;
  44965. }
  44966. return false;
  44967. };
  44968. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44969. return "PBRBaseSimpleMaterial";
  44970. };
  44971. __decorate([
  44972. BABYLON.serialize(),
  44973. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44974. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44975. __decorate([
  44976. BABYLON.serialize(),
  44977. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44978. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44979. __decorate([
  44980. BABYLON.serializeAsTexture(),
  44981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44982. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44983. __decorate([
  44984. BABYLON.serialize(),
  44985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44986. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44987. __decorate([
  44988. BABYLON.serialize(),
  44989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44990. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44991. __decorate([
  44992. BABYLON.serializeAsTexture(),
  44993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44994. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44995. __decorate([
  44996. BABYLON.serializeAsColor3("emissive"),
  44997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44998. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44999. __decorate([
  45000. BABYLON.serializeAsTexture(),
  45001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45002. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45003. __decorate([
  45004. BABYLON.serialize(),
  45005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45006. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45007. __decorate([
  45008. BABYLON.serializeAsTexture(),
  45009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45010. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45011. __decorate([
  45012. BABYLON.serialize(),
  45013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45014. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45015. __decorate([
  45016. BABYLON.serialize()
  45017. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45018. __decorate([
  45019. BABYLON.serializeAsTexture(),
  45020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45021. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45022. __decorate([
  45023. BABYLON.serialize(),
  45024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45025. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45026. return PBRBaseSimpleMaterial;
  45027. }(BABYLON.PBRBaseMaterial));
  45028. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45029. })(BABYLON || (BABYLON = {}));
  45030. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45031. var BABYLON;
  45032. (function (BABYLON) {
  45033. /**
  45034. * The Physically based material of BJS.
  45035. *
  45036. * This offers the main features of a standard PBR material.
  45037. * For more information, please refer to the documentation :
  45038. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45039. */
  45040. var PBRMaterial = /** @class */ (function (_super) {
  45041. __extends(PBRMaterial, _super);
  45042. /**
  45043. * Instantiates a new PBRMaterial instance.
  45044. *
  45045. * @param name The material name
  45046. * @param scene The scene the material will be use in.
  45047. */
  45048. function PBRMaterial(name, scene) {
  45049. var _this = _super.call(this, name, scene) || this;
  45050. /**
  45051. * Intensity of the direct lights e.g. the four lights available in your scene.
  45052. * This impacts both the direct diffuse and specular highlights.
  45053. */
  45054. _this.directIntensity = 1.0;
  45055. /**
  45056. * Intensity of the emissive part of the material.
  45057. * This helps controlling the emissive effect without modifying the emissive color.
  45058. */
  45059. _this.emissiveIntensity = 1.0;
  45060. /**
  45061. * Intensity of the environment e.g. how much the environment will light the object
  45062. * either through harmonics for rough material or through the refelction for shiny ones.
  45063. */
  45064. _this.environmentIntensity = 1.0;
  45065. /**
  45066. * This is a special control allowing the reduction of the specular highlights coming from the
  45067. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45068. */
  45069. _this.specularIntensity = 1.0;
  45070. /**
  45071. * Debug Control allowing disabling the bump map on this material.
  45072. */
  45073. _this.disableBumpMap = false;
  45074. /**
  45075. * AKA Occlusion Texture Intensity in other nomenclature.
  45076. */
  45077. _this.ambientTextureStrength = 1.0;
  45078. /**
  45079. * The color of a material in ambient lighting.
  45080. */
  45081. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45082. /**
  45083. * AKA Diffuse Color in other nomenclature.
  45084. */
  45085. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45086. /**
  45087. * AKA Specular Color in other nomenclature.
  45088. */
  45089. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45090. /**
  45091. * The color reflected from the material.
  45092. */
  45093. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45094. /**
  45095. * The color emitted from the material.
  45096. */
  45097. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45098. /**
  45099. * AKA Glossiness in other nomenclature.
  45100. */
  45101. _this.microSurface = 1.0;
  45102. /**
  45103. * source material index of refraction (IOR)' / 'destination material IOR.
  45104. */
  45105. _this.indexOfRefraction = 0.66;
  45106. /**
  45107. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45108. */
  45109. _this.invertRefractionY = false;
  45110. /**
  45111. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45112. * Materials half opaque for instance using refraction could benefit from this control.
  45113. */
  45114. _this.linkRefractionWithTransparency = false;
  45115. _this.useLightmapAsShadowmap = false;
  45116. /**
  45117. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45118. */
  45119. _this.useAlphaFromAlbedoTexture = false;
  45120. /**
  45121. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45122. */
  45123. _this.forceAlphaTest = false;
  45124. /**
  45125. * Defines the alpha limits in alpha test mode.
  45126. */
  45127. _this.alphaCutOff = 0.4;
  45128. /**
  45129. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45130. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45131. */
  45132. _this.useSpecularOverAlpha = true;
  45133. /**
  45134. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45135. */
  45136. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45137. /**
  45138. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45139. */
  45140. _this.useRoughnessFromMetallicTextureAlpha = true;
  45141. /**
  45142. * Specifies if the metallic texture contains the roughness information in its green channel.
  45143. */
  45144. _this.useRoughnessFromMetallicTextureGreen = false;
  45145. /**
  45146. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45147. */
  45148. _this.useMetallnessFromMetallicTextureBlue = false;
  45149. /**
  45150. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45151. */
  45152. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45153. /**
  45154. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45155. */
  45156. _this.useAmbientInGrayScale = false;
  45157. /**
  45158. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45159. * The material will try to infer what glossiness each pixel should be.
  45160. */
  45161. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45162. /**
  45163. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45164. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45165. */
  45166. _this.useRadianceOverAlpha = true;
  45167. /**
  45168. * Allows using an object space normal map (instead of tangent space).
  45169. */
  45170. _this.useObjectSpaceNormalMap = false;
  45171. /**
  45172. * Allows using the bump map in parallax mode.
  45173. */
  45174. _this.useParallax = false;
  45175. /**
  45176. * Allows using the bump map in parallax occlusion mode.
  45177. */
  45178. _this.useParallaxOcclusion = false;
  45179. /**
  45180. * Controls the scale bias of the parallax mode.
  45181. */
  45182. _this.parallaxScaleBias = 0.05;
  45183. /**
  45184. * If sets to true, disables all the lights affecting the material.
  45185. */
  45186. _this.disableLighting = false;
  45187. /**
  45188. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45189. */
  45190. _this.forceIrradianceInFragment = false;
  45191. /**
  45192. * Number of Simultaneous lights allowed on the material.
  45193. */
  45194. _this.maxSimultaneousLights = 4;
  45195. /**
  45196. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45197. */
  45198. _this.invertNormalMapX = false;
  45199. /**
  45200. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45201. */
  45202. _this.invertNormalMapY = false;
  45203. /**
  45204. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45205. */
  45206. _this.twoSidedLighting = false;
  45207. /**
  45208. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45209. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45210. */
  45211. _this.useAlphaFresnel = false;
  45212. /**
  45213. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45214. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45215. */
  45216. _this.useLinearAlphaFresnel = false;
  45217. /**
  45218. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45219. * And/Or occlude the blended part.
  45220. */
  45221. _this.environmentBRDFTexture = null;
  45222. /**
  45223. * Force normal to face away from face.
  45224. */
  45225. _this.forceNormalForward = false;
  45226. /**
  45227. * Enables specular anti aliasing in the PBR shader.
  45228. * It will both interacts on the Geometry for analytical and IBL lighting.
  45229. * It also prefilter the roughness map based on the bump values.
  45230. */
  45231. _this.enableSpecularAntiAliasing = false;
  45232. /**
  45233. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45234. * makes the reflect vector face the model (under horizon).
  45235. */
  45236. _this.useHorizonOcclusion = true;
  45237. /**
  45238. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45239. * too much the area relying on ambient texture to define their ambient occlusion.
  45240. */
  45241. _this.useRadianceOcclusion = true;
  45242. /**
  45243. * If set to true, no lighting calculations will be applied.
  45244. */
  45245. _this.unlit = false;
  45246. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45247. return _this;
  45248. }
  45249. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45250. /**
  45251. * BJS is using an harcoded light falloff based on a manually sets up range.
  45252. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45253. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45254. */
  45255. get: function () {
  45256. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45257. },
  45258. /**
  45259. * BJS is using an harcoded light falloff based on a manually sets up range.
  45260. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45261. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45262. */
  45263. set: function (value) {
  45264. if (value !== this.usePhysicalLightFalloff) {
  45265. // Ensure the effect will be rebuilt.
  45266. this._markAllSubMeshesAsTexturesDirty();
  45267. if (value) {
  45268. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45269. }
  45270. else {
  45271. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45272. }
  45273. }
  45274. },
  45275. enumerable: true,
  45276. configurable: true
  45277. });
  45278. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45279. /**
  45280. * In order to support the falloff compatibility with gltf, a special mode has been added
  45281. * to reproduce the gltf light falloff.
  45282. */
  45283. get: function () {
  45284. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45285. },
  45286. /**
  45287. * In order to support the falloff compatibility with gltf, a special mode has been added
  45288. * to reproduce the gltf light falloff.
  45289. */
  45290. set: function (value) {
  45291. if (value !== this.useGLTFLightFalloff) {
  45292. // Ensure the effect will be rebuilt.
  45293. this._markAllSubMeshesAsTexturesDirty();
  45294. if (value) {
  45295. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45296. }
  45297. else {
  45298. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45299. }
  45300. }
  45301. },
  45302. enumerable: true,
  45303. configurable: true
  45304. });
  45305. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45306. /**
  45307. * Gets the image processing configuration used either in this material.
  45308. */
  45309. get: function () {
  45310. return this._imageProcessingConfiguration;
  45311. },
  45312. /**
  45313. * Sets the Default image processing configuration used either in the this material.
  45314. *
  45315. * If sets to null, the scene one is in use.
  45316. */
  45317. set: function (value) {
  45318. this._attachImageProcessingConfiguration(value);
  45319. // Ensure the effect will be rebuilt.
  45320. this._markAllSubMeshesAsTexturesDirty();
  45321. },
  45322. enumerable: true,
  45323. configurable: true
  45324. });
  45325. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45326. /**
  45327. * Gets wether the color curves effect is enabled.
  45328. */
  45329. get: function () {
  45330. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45331. },
  45332. /**
  45333. * Sets wether the color curves effect is enabled.
  45334. */
  45335. set: function (value) {
  45336. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45337. },
  45338. enumerable: true,
  45339. configurable: true
  45340. });
  45341. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45342. /**
  45343. * Gets wether the color grading effect is enabled.
  45344. */
  45345. get: function () {
  45346. return this.imageProcessingConfiguration.colorGradingEnabled;
  45347. },
  45348. /**
  45349. * Gets wether the color grading effect is enabled.
  45350. */
  45351. set: function (value) {
  45352. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45353. },
  45354. enumerable: true,
  45355. configurable: true
  45356. });
  45357. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45358. /**
  45359. * Gets wether tonemapping is enabled or not.
  45360. */
  45361. get: function () {
  45362. return this._imageProcessingConfiguration.toneMappingEnabled;
  45363. },
  45364. /**
  45365. * Sets wether tonemapping is enabled or not
  45366. */
  45367. set: function (value) {
  45368. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45369. },
  45370. enumerable: true,
  45371. configurable: true
  45372. });
  45373. ;
  45374. ;
  45375. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45376. /**
  45377. * The camera exposure used on this material.
  45378. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45379. * This corresponds to a photographic exposure.
  45380. */
  45381. get: function () {
  45382. return this._imageProcessingConfiguration.exposure;
  45383. },
  45384. /**
  45385. * The camera exposure used on this material.
  45386. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45387. * This corresponds to a photographic exposure.
  45388. */
  45389. set: function (value) {
  45390. this._imageProcessingConfiguration.exposure = value;
  45391. },
  45392. enumerable: true,
  45393. configurable: true
  45394. });
  45395. ;
  45396. ;
  45397. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45398. /**
  45399. * Gets The camera contrast used on this material.
  45400. */
  45401. get: function () {
  45402. return this._imageProcessingConfiguration.contrast;
  45403. },
  45404. /**
  45405. * Sets The camera contrast used on this material.
  45406. */
  45407. set: function (value) {
  45408. this._imageProcessingConfiguration.contrast = value;
  45409. },
  45410. enumerable: true,
  45411. configurable: true
  45412. });
  45413. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45414. /**
  45415. * Gets the Color Grading 2D Lookup Texture.
  45416. */
  45417. get: function () {
  45418. return this._imageProcessingConfiguration.colorGradingTexture;
  45419. },
  45420. /**
  45421. * Sets the Color Grading 2D Lookup Texture.
  45422. */
  45423. set: function (value) {
  45424. this._imageProcessingConfiguration.colorGradingTexture = value;
  45425. },
  45426. enumerable: true,
  45427. configurable: true
  45428. });
  45429. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45430. /**
  45431. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45432. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45433. * 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;
  45434. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45435. */
  45436. get: function () {
  45437. return this._imageProcessingConfiguration.colorCurves;
  45438. },
  45439. /**
  45440. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45441. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45442. * 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;
  45443. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45444. */
  45445. set: function (value) {
  45446. this._imageProcessingConfiguration.colorCurves = value;
  45447. },
  45448. enumerable: true,
  45449. configurable: true
  45450. });
  45451. /**
  45452. * Returns the name of this material class.
  45453. */
  45454. PBRMaterial.prototype.getClassName = function () {
  45455. return "PBRMaterial";
  45456. };
  45457. /**
  45458. * Returns an array of the actively used textures.
  45459. * @returns - Array of BaseTextures
  45460. */
  45461. PBRMaterial.prototype.getActiveTextures = function () {
  45462. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45463. if (this._albedoTexture) {
  45464. activeTextures.push(this._albedoTexture);
  45465. }
  45466. if (this._ambientTexture) {
  45467. activeTextures.push(this._ambientTexture);
  45468. }
  45469. if (this._opacityTexture) {
  45470. activeTextures.push(this._opacityTexture);
  45471. }
  45472. if (this._reflectionTexture) {
  45473. activeTextures.push(this._reflectionTexture);
  45474. }
  45475. if (this._emissiveTexture) {
  45476. activeTextures.push(this._emissiveTexture);
  45477. }
  45478. if (this._reflectivityTexture) {
  45479. activeTextures.push(this._reflectivityTexture);
  45480. }
  45481. if (this._metallicTexture) {
  45482. activeTextures.push(this._metallicTexture);
  45483. }
  45484. if (this._microSurfaceTexture) {
  45485. activeTextures.push(this._microSurfaceTexture);
  45486. }
  45487. if (this._bumpTexture) {
  45488. activeTextures.push(this._bumpTexture);
  45489. }
  45490. if (this._lightmapTexture) {
  45491. activeTextures.push(this._lightmapTexture);
  45492. }
  45493. if (this._refractionTexture) {
  45494. activeTextures.push(this._refractionTexture);
  45495. }
  45496. return activeTextures;
  45497. };
  45498. /**
  45499. * Checks to see if a texture is used in the material.
  45500. * @param texture - Base texture to use.
  45501. * @returns - Boolean specifying if a texture is used in the material.
  45502. */
  45503. PBRMaterial.prototype.hasTexture = function (texture) {
  45504. if (_super.prototype.hasTexture.call(this, texture)) {
  45505. return true;
  45506. }
  45507. if (this._albedoTexture === texture) {
  45508. return true;
  45509. }
  45510. if (this._ambientTexture === texture) {
  45511. return true;
  45512. }
  45513. if (this._opacityTexture === texture) {
  45514. return true;
  45515. }
  45516. if (this._reflectionTexture === texture) {
  45517. return true;
  45518. }
  45519. if (this._reflectivityTexture === texture) {
  45520. return true;
  45521. }
  45522. if (this._metallicTexture === texture) {
  45523. return true;
  45524. }
  45525. if (this._microSurfaceTexture === texture) {
  45526. return true;
  45527. }
  45528. if (this._bumpTexture === texture) {
  45529. return true;
  45530. }
  45531. if (this._lightmapTexture === texture) {
  45532. return true;
  45533. }
  45534. if (this._refractionTexture === texture) {
  45535. return true;
  45536. }
  45537. return false;
  45538. };
  45539. /**
  45540. * Makes a duplicate of the current material.
  45541. * @param name - name to use for the new material.
  45542. */
  45543. PBRMaterial.prototype.clone = function (name) {
  45544. var _this = this;
  45545. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45546. clone.id = name;
  45547. clone.name = name;
  45548. return clone;
  45549. };
  45550. /**
  45551. * Serializes this PBR Material.
  45552. * @returns - An object with the serialized material.
  45553. */
  45554. PBRMaterial.prototype.serialize = function () {
  45555. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45556. serializationObject.customType = "BABYLON.PBRMaterial";
  45557. return serializationObject;
  45558. };
  45559. // Statics
  45560. /**
  45561. * Parses a PBR Material from a serialized object.
  45562. * @param source - Serialized object.
  45563. * @param scene - BJS scene instance.
  45564. * @param rootUrl - url for the scene object
  45565. * @returns - PBRMaterial
  45566. */
  45567. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45568. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45569. };
  45570. /**
  45571. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45572. */
  45573. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45574. /**
  45575. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45576. */
  45577. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45578. /**
  45579. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45580. */
  45581. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45582. /**
  45583. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45584. * They are also discarded below the alpha cutoff threshold to improve performances.
  45585. */
  45586. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "directIntensity", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45603. __decorate([
  45604. BABYLON.serialize(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45607. __decorate([
  45608. BABYLON.serializeAsTexture(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45611. __decorate([
  45612. BABYLON.serializeAsTexture(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45619. __decorate([
  45620. BABYLON.serializeAsTexture(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45622. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45623. __decorate([
  45624. BABYLON.serializeAsTexture(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45627. __decorate([
  45628. BABYLON.serializeAsTexture(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45630. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45631. __decorate([
  45632. BABYLON.serializeAsTexture(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45634. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45635. __decorate([
  45636. BABYLON.serializeAsTexture(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45638. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45639. __decorate([
  45640. BABYLON.serialize(),
  45641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45642. ], PBRMaterial.prototype, "metallic", void 0);
  45643. __decorate([
  45644. BABYLON.serialize(),
  45645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45646. ], PBRMaterial.prototype, "roughness", void 0);
  45647. __decorate([
  45648. BABYLON.serializeAsTexture(),
  45649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45650. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45651. __decorate([
  45652. BABYLON.serializeAsTexture(),
  45653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45654. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45655. __decorate([
  45656. BABYLON.serializeAsTexture(),
  45657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45658. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45659. __decorate([
  45660. BABYLON.serializeAsTexture(),
  45661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45662. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45663. __decorate([
  45664. BABYLON.serializeAsColor3("ambient"),
  45665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45666. ], PBRMaterial.prototype, "ambientColor", void 0);
  45667. __decorate([
  45668. BABYLON.serializeAsColor3("albedo"),
  45669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45670. ], PBRMaterial.prototype, "albedoColor", void 0);
  45671. __decorate([
  45672. BABYLON.serializeAsColor3("reflectivity"),
  45673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45674. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45675. __decorate([
  45676. BABYLON.serializeAsColor3("reflection"),
  45677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45678. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45679. __decorate([
  45680. BABYLON.serializeAsColor3("emissive"),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45682. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45683. __decorate([
  45684. BABYLON.serialize(),
  45685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45686. ], PBRMaterial.prototype, "microSurface", void 0);
  45687. __decorate([
  45688. BABYLON.serialize(),
  45689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45690. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45691. __decorate([
  45692. BABYLON.serialize(),
  45693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45694. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45695. __decorate([
  45696. BABYLON.serialize(),
  45697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45698. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45699. __decorate([
  45700. BABYLON.serialize(),
  45701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45702. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45703. __decorate([
  45704. BABYLON.serialize(),
  45705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45706. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45707. __decorate([
  45708. BABYLON.serialize(),
  45709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45710. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45711. __decorate([
  45712. BABYLON.serialize(),
  45713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45714. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45715. __decorate([
  45716. BABYLON.serialize(),
  45717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45718. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45719. __decorate([
  45720. BABYLON.serialize(),
  45721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45722. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45723. __decorate([
  45724. BABYLON.serialize(),
  45725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45726. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45727. __decorate([
  45728. BABYLON.serialize(),
  45729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45730. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45731. __decorate([
  45732. BABYLON.serialize(),
  45733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45734. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45735. __decorate([
  45736. BABYLON.serialize(),
  45737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45738. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45739. __decorate([
  45740. BABYLON.serialize(),
  45741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45742. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45743. __decorate([
  45744. BABYLON.serialize(),
  45745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45746. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45747. __decorate([
  45748. BABYLON.serialize()
  45749. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45750. __decorate([
  45751. BABYLON.serialize()
  45752. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45753. __decorate([
  45754. BABYLON.serialize(),
  45755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45756. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45757. __decorate([
  45758. BABYLON.serialize(),
  45759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45760. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45761. __decorate([
  45762. BABYLON.serialize(),
  45763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45764. ], PBRMaterial.prototype, "useParallax", void 0);
  45765. __decorate([
  45766. BABYLON.serialize(),
  45767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45768. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45769. __decorate([
  45770. BABYLON.serialize(),
  45771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45772. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45773. __decorate([
  45774. BABYLON.serialize(),
  45775. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45776. ], PBRMaterial.prototype, "disableLighting", void 0);
  45777. __decorate([
  45778. BABYLON.serialize(),
  45779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45780. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45781. __decorate([
  45782. BABYLON.serialize(),
  45783. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45784. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45785. __decorate([
  45786. BABYLON.serialize(),
  45787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45788. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45789. __decorate([
  45790. BABYLON.serialize(),
  45791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45792. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45793. __decorate([
  45794. BABYLON.serialize(),
  45795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45796. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45797. __decorate([
  45798. BABYLON.serialize(),
  45799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45800. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45801. __decorate([
  45802. BABYLON.serialize(),
  45803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45804. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45805. __decorate([
  45806. BABYLON.serializeAsTexture(),
  45807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45808. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45809. __decorate([
  45810. BABYLON.serialize(),
  45811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45812. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45813. __decorate([
  45814. BABYLON.serialize(),
  45815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45816. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45817. __decorate([
  45818. BABYLON.serialize(),
  45819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45820. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45821. __decorate([
  45822. BABYLON.serialize(),
  45823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45824. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45825. __decorate([
  45826. BABYLON.serialize(),
  45827. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45828. ], PBRMaterial.prototype, "unlit", void 0);
  45829. return PBRMaterial;
  45830. }(BABYLON.PBRBaseMaterial));
  45831. BABYLON.PBRMaterial = PBRMaterial;
  45832. })(BABYLON || (BABYLON = {}));
  45833. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45834. var BABYLON;
  45835. (function (BABYLON) {
  45836. /**
  45837. * The PBR material of BJS following the metal roughness convention.
  45838. *
  45839. * This fits to the PBR convention in the GLTF definition:
  45840. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45841. */
  45842. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45843. __extends(PBRMetallicRoughnessMaterial, _super);
  45844. /**
  45845. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45846. *
  45847. * @param name The material name
  45848. * @param scene The scene the material will be use in.
  45849. */
  45850. function PBRMetallicRoughnessMaterial(name, scene) {
  45851. var _this = _super.call(this, name, scene) || this;
  45852. _this._useRoughnessFromMetallicTextureAlpha = false;
  45853. _this._useRoughnessFromMetallicTextureGreen = true;
  45854. _this._useMetallnessFromMetallicTextureBlue = true;
  45855. _this.metallic = 1.0;
  45856. _this.roughness = 1.0;
  45857. return _this;
  45858. }
  45859. /**
  45860. * Return the currrent class name of the material.
  45861. */
  45862. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45863. return "PBRMetallicRoughnessMaterial";
  45864. };
  45865. /**
  45866. * Return the active textures of the material.
  45867. */
  45868. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45869. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45870. if (this.baseTexture) {
  45871. activeTextures.push(this.baseTexture);
  45872. }
  45873. if (this.metallicRoughnessTexture) {
  45874. activeTextures.push(this.metallicRoughnessTexture);
  45875. }
  45876. return activeTextures;
  45877. };
  45878. /**
  45879. * Checks to see if a texture is used in the material.
  45880. * @param texture - Base texture to use.
  45881. * @returns - Boolean specifying if a texture is used in the material.
  45882. */
  45883. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45884. if (_super.prototype.hasTexture.call(this, texture)) {
  45885. return true;
  45886. }
  45887. if (this.baseTexture === texture) {
  45888. return true;
  45889. }
  45890. if (this.metallicRoughnessTexture === texture) {
  45891. return true;
  45892. }
  45893. return false;
  45894. };
  45895. /**
  45896. * Makes a duplicate of the current material.
  45897. * @param name - name to use for the new material.
  45898. */
  45899. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45900. var _this = this;
  45901. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45902. clone.id = name;
  45903. clone.name = name;
  45904. return clone;
  45905. };
  45906. /**
  45907. * Serialize the material to a parsable JSON object.
  45908. */
  45909. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45910. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45911. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45912. return serializationObject;
  45913. };
  45914. /**
  45915. * Parses a JSON object correponding to the serialize function.
  45916. */
  45917. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45918. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45919. };
  45920. __decorate([
  45921. BABYLON.serializeAsColor3(),
  45922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45923. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45924. __decorate([
  45925. BABYLON.serializeAsTexture(),
  45926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45927. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45928. __decorate([
  45929. BABYLON.serialize(),
  45930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45931. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45932. __decorate([
  45933. BABYLON.serialize(),
  45934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45935. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45936. __decorate([
  45937. BABYLON.serializeAsTexture(),
  45938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45939. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45940. return PBRMetallicRoughnessMaterial;
  45941. }(BABYLON.PBRBaseSimpleMaterial));
  45942. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45943. })(BABYLON || (BABYLON = {}));
  45944. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45945. var BABYLON;
  45946. (function (BABYLON) {
  45947. /**
  45948. * The PBR material of BJS following the specular glossiness convention.
  45949. *
  45950. * This fits to the PBR convention in the GLTF definition:
  45951. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45952. */
  45953. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45954. __extends(PBRSpecularGlossinessMaterial, _super);
  45955. /**
  45956. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45957. *
  45958. * @param name The material name
  45959. * @param scene The scene the material will be use in.
  45960. */
  45961. function PBRSpecularGlossinessMaterial(name, scene) {
  45962. var _this = _super.call(this, name, scene) || this;
  45963. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45964. return _this;
  45965. }
  45966. /**
  45967. * Return the currrent class name of the material.
  45968. */
  45969. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45970. return "PBRSpecularGlossinessMaterial";
  45971. };
  45972. /**
  45973. * Return the active textures of the material.
  45974. */
  45975. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45976. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45977. if (this.diffuseTexture) {
  45978. activeTextures.push(this.diffuseTexture);
  45979. }
  45980. if (this.specularGlossinessTexture) {
  45981. activeTextures.push(this.specularGlossinessTexture);
  45982. }
  45983. return activeTextures;
  45984. };
  45985. /**
  45986. * Checks to see if a texture is used in the material.
  45987. * @param texture - Base texture to use.
  45988. * @returns - Boolean specifying if a texture is used in the material.
  45989. */
  45990. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45991. if (_super.prototype.hasTexture.call(this, texture)) {
  45992. return true;
  45993. }
  45994. if (this.diffuseTexture === texture) {
  45995. return true;
  45996. }
  45997. if (this.specularGlossinessTexture === texture) {
  45998. return true;
  45999. }
  46000. return false;
  46001. };
  46002. /**
  46003. * Makes a duplicate of the current material.
  46004. * @param name - name to use for the new material.
  46005. */
  46006. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46007. var _this = this;
  46008. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46009. clone.id = name;
  46010. clone.name = name;
  46011. return clone;
  46012. };
  46013. /**
  46014. * Serialize the material to a parsable JSON object.
  46015. */
  46016. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46017. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46018. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46019. return serializationObject;
  46020. };
  46021. /**
  46022. * Parses a JSON object correponding to the serialize function.
  46023. */
  46024. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46025. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46026. };
  46027. __decorate([
  46028. BABYLON.serializeAsColor3("diffuse"),
  46029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46030. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46031. __decorate([
  46032. BABYLON.serializeAsTexture(),
  46033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46034. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46035. __decorate([
  46036. BABYLON.serializeAsColor3("specular"),
  46037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46038. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46039. __decorate([
  46040. BABYLON.serialize(),
  46041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46042. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46043. __decorate([
  46044. BABYLON.serializeAsTexture(),
  46045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46046. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46047. return PBRSpecularGlossinessMaterial;
  46048. }(BABYLON.PBRBaseSimpleMaterial));
  46049. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46050. })(BABYLON || (BABYLON = {}));
  46051. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46052. var BABYLON;
  46053. (function (BABYLON) {
  46054. BABYLON.CameraInputTypes = {};
  46055. var CameraInputsManager = /** @class */ (function () {
  46056. function CameraInputsManager(camera) {
  46057. this.attached = {};
  46058. this.camera = camera;
  46059. this.checkInputs = function () { };
  46060. }
  46061. /**
  46062. * Add an input method to a camera
  46063. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46064. * @param input camera input method
  46065. */
  46066. CameraInputsManager.prototype.add = function (input) {
  46067. var type = input.getSimpleName();
  46068. if (this.attached[type]) {
  46069. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46070. return;
  46071. }
  46072. this.attached[type] = input;
  46073. input.camera = this.camera;
  46074. //for checkInputs, we are dynamically creating a function
  46075. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46076. if (input.checkInputs) {
  46077. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46078. }
  46079. if (this.attachedElement) {
  46080. input.attachControl(this.attachedElement);
  46081. }
  46082. };
  46083. /**
  46084. * Remove a specific input method from a camera
  46085. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46086. * @param inputToRemove camera input method
  46087. */
  46088. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46089. for (var cam in this.attached) {
  46090. var input = this.attached[cam];
  46091. if (input === inputToRemove) {
  46092. input.detachControl(this.attachedElement);
  46093. input.camera = null;
  46094. delete this.attached[cam];
  46095. this.rebuildInputCheck();
  46096. }
  46097. }
  46098. };
  46099. CameraInputsManager.prototype.removeByType = function (inputType) {
  46100. for (var cam in this.attached) {
  46101. var input = this.attached[cam];
  46102. if (input.getClassName() === inputType) {
  46103. input.detachControl(this.attachedElement);
  46104. input.camera = null;
  46105. delete this.attached[cam];
  46106. this.rebuildInputCheck();
  46107. }
  46108. }
  46109. };
  46110. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46111. var current = this.checkInputs;
  46112. return function () {
  46113. current();
  46114. fn();
  46115. };
  46116. };
  46117. CameraInputsManager.prototype.attachInput = function (input) {
  46118. if (this.attachedElement) {
  46119. input.attachControl(this.attachedElement, this.noPreventDefault);
  46120. }
  46121. };
  46122. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46123. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46124. if (this.attachedElement) {
  46125. return;
  46126. }
  46127. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46128. this.attachedElement = element;
  46129. this.noPreventDefault = noPreventDefault;
  46130. for (var cam in this.attached) {
  46131. this.attached[cam].attachControl(element, noPreventDefault);
  46132. }
  46133. };
  46134. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46135. if (disconnect === void 0) { disconnect = false; }
  46136. if (this.attachedElement !== element) {
  46137. return;
  46138. }
  46139. for (var cam in this.attached) {
  46140. this.attached[cam].detachControl(element);
  46141. if (disconnect) {
  46142. this.attached[cam].camera = null;
  46143. }
  46144. }
  46145. this.attachedElement = null;
  46146. };
  46147. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46148. this.checkInputs = function () { };
  46149. for (var cam in this.attached) {
  46150. var input = this.attached[cam];
  46151. if (input.checkInputs) {
  46152. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46153. }
  46154. }
  46155. };
  46156. /**
  46157. * Remove all attached input methods from a camera
  46158. */
  46159. CameraInputsManager.prototype.clear = function () {
  46160. if (this.attachedElement) {
  46161. this.detachElement(this.attachedElement, true);
  46162. }
  46163. this.attached = {};
  46164. this.attachedElement = null;
  46165. this.checkInputs = function () { };
  46166. };
  46167. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46168. var inputs = {};
  46169. for (var cam in this.attached) {
  46170. var input = this.attached[cam];
  46171. var res = BABYLON.SerializationHelper.Serialize(input);
  46172. inputs[input.getClassName()] = res;
  46173. }
  46174. serializedCamera.inputsmgr = inputs;
  46175. };
  46176. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46177. var parsedInputs = parsedCamera.inputsmgr;
  46178. if (parsedInputs) {
  46179. this.clear();
  46180. for (var n in parsedInputs) {
  46181. var construct = BABYLON.CameraInputTypes[n];
  46182. if (construct) {
  46183. var parsedinput = parsedInputs[n];
  46184. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46185. this.add(input);
  46186. }
  46187. }
  46188. }
  46189. else {
  46190. //2016-03-08 this part is for managing backward compatibility
  46191. for (var n in this.attached) {
  46192. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46193. if (construct) {
  46194. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46195. this.remove(this.attached[n]);
  46196. this.add(input);
  46197. }
  46198. }
  46199. }
  46200. };
  46201. return CameraInputsManager;
  46202. }());
  46203. BABYLON.CameraInputsManager = CameraInputsManager;
  46204. })(BABYLON || (BABYLON = {}));
  46205. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46206. var BABYLON;
  46207. (function (BABYLON) {
  46208. var TargetCamera = /** @class */ (function (_super) {
  46209. __extends(TargetCamera, _super);
  46210. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46211. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46212. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46213. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46214. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46215. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46216. _this.speed = 2.0;
  46217. _this.noRotationConstraint = false;
  46218. _this.lockedTarget = null;
  46219. /** @hidden */
  46220. _this._currentTarget = BABYLON.Vector3.Zero();
  46221. /** @hidden */
  46222. _this._viewMatrix = BABYLON.Matrix.Zero();
  46223. /** @hidden */
  46224. _this._camMatrix = BABYLON.Matrix.Zero();
  46225. /** @hidden */
  46226. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46227. /** @hidden */
  46228. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46229. /** @hidden */
  46230. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46231. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46232. /** @hidden */
  46233. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46234. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46235. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46236. return _this;
  46237. }
  46238. TargetCamera.prototype.getFrontPosition = function (distance) {
  46239. this.getWorldMatrix();
  46240. var direction = this.getTarget().subtract(this.position);
  46241. direction.normalize();
  46242. direction.scaleInPlace(distance);
  46243. return this.globalPosition.add(direction);
  46244. };
  46245. /** @hidden */
  46246. TargetCamera.prototype._getLockedTargetPosition = function () {
  46247. if (!this.lockedTarget) {
  46248. return null;
  46249. }
  46250. if (this.lockedTarget.absolutePosition) {
  46251. this.lockedTarget.computeWorldMatrix();
  46252. }
  46253. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46254. };
  46255. TargetCamera.prototype.storeState = function () {
  46256. this._storedPosition = this.position.clone();
  46257. this._storedRotation = this.rotation.clone();
  46258. if (this.rotationQuaternion) {
  46259. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46260. }
  46261. return _super.prototype.storeState.call(this);
  46262. };
  46263. /**
  46264. * Restored camera state. You must call storeState() first
  46265. * @returns whether it was successful or not
  46266. * @hidden
  46267. */
  46268. TargetCamera.prototype._restoreStateValues = function () {
  46269. if (!_super.prototype._restoreStateValues.call(this)) {
  46270. return false;
  46271. }
  46272. this.position = this._storedPosition.clone();
  46273. this.rotation = this._storedRotation.clone();
  46274. if (this.rotationQuaternion) {
  46275. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46276. }
  46277. this.cameraDirection.copyFromFloats(0, 0, 0);
  46278. this.cameraRotation.copyFromFloats(0, 0);
  46279. return true;
  46280. };
  46281. // Cache
  46282. /** @hidden */
  46283. TargetCamera.prototype._initCache = function () {
  46284. _super.prototype._initCache.call(this);
  46285. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46286. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46287. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46288. };
  46289. /** @hidden */
  46290. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46291. if (!ignoreParentClass) {
  46292. _super.prototype._updateCache.call(this);
  46293. }
  46294. var lockedTargetPosition = this._getLockedTargetPosition();
  46295. if (!lockedTargetPosition) {
  46296. this._cache.lockedTarget = null;
  46297. }
  46298. else {
  46299. if (!this._cache.lockedTarget) {
  46300. this._cache.lockedTarget = lockedTargetPosition.clone();
  46301. }
  46302. else {
  46303. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46304. }
  46305. }
  46306. this._cache.rotation.copyFrom(this.rotation);
  46307. if (this.rotationQuaternion)
  46308. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46309. };
  46310. // Synchronized
  46311. /** @hidden */
  46312. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46313. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46314. return false;
  46315. }
  46316. var lockedTargetPosition = this._getLockedTargetPosition();
  46317. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46318. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46319. };
  46320. // Methods
  46321. /** @hidden */
  46322. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46323. var engine = this.getEngine();
  46324. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46325. };
  46326. // Target
  46327. /** @hidden */
  46328. TargetCamera.prototype.setTarget = function (target) {
  46329. this.upVector.normalize();
  46330. if (this.position.z === target.z) {
  46331. this.position.z += BABYLON.Epsilon;
  46332. }
  46333. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46334. this._camMatrix.invert();
  46335. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46336. var vDir = target.subtract(this.position);
  46337. if (vDir.x >= 0.0) {
  46338. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46339. }
  46340. else {
  46341. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46342. }
  46343. this.rotation.z = 0;
  46344. if (isNaN(this.rotation.x)) {
  46345. this.rotation.x = 0;
  46346. }
  46347. if (isNaN(this.rotation.y)) {
  46348. this.rotation.y = 0;
  46349. }
  46350. if (isNaN(this.rotation.z)) {
  46351. this.rotation.z = 0;
  46352. }
  46353. if (this.rotationQuaternion) {
  46354. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46355. }
  46356. };
  46357. /**
  46358. * Return the current target position of the camera. This value is expressed in local space.
  46359. */
  46360. TargetCamera.prototype.getTarget = function () {
  46361. return this._currentTarget;
  46362. };
  46363. /** @hidden */
  46364. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46365. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46366. };
  46367. /** @hidden */
  46368. TargetCamera.prototype._updatePosition = function () {
  46369. if (this.parent) {
  46370. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46371. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46372. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46373. return;
  46374. }
  46375. this.position.addInPlace(this.cameraDirection);
  46376. };
  46377. /** @hidden */
  46378. TargetCamera.prototype._checkInputs = function () {
  46379. var needToMove = this._decideIfNeedsToMove();
  46380. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46381. // Move
  46382. if (needToMove) {
  46383. this._updatePosition();
  46384. }
  46385. // Rotate
  46386. if (needToRotate) {
  46387. this.rotation.x += this.cameraRotation.x;
  46388. this.rotation.y += this.cameraRotation.y;
  46389. //rotate, if quaternion is set and rotation was used
  46390. if (this.rotationQuaternion) {
  46391. var len = this.rotation.lengthSquared();
  46392. if (len) {
  46393. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46394. }
  46395. }
  46396. if (!this.noRotationConstraint) {
  46397. var limit = (Math.PI / 2) * 0.95;
  46398. if (this.rotation.x > limit)
  46399. this.rotation.x = limit;
  46400. if (this.rotation.x < -limit)
  46401. this.rotation.x = -limit;
  46402. }
  46403. }
  46404. // Inertia
  46405. if (needToMove) {
  46406. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46407. this.cameraDirection.x = 0;
  46408. }
  46409. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46410. this.cameraDirection.y = 0;
  46411. }
  46412. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46413. this.cameraDirection.z = 0;
  46414. }
  46415. this.cameraDirection.scaleInPlace(this.inertia);
  46416. }
  46417. if (needToRotate) {
  46418. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46419. this.cameraRotation.x = 0;
  46420. }
  46421. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46422. this.cameraRotation.y = 0;
  46423. }
  46424. this.cameraRotation.scaleInPlace(this.inertia);
  46425. }
  46426. _super.prototype._checkInputs.call(this);
  46427. };
  46428. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46429. if (this.rotationQuaternion) {
  46430. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46431. }
  46432. else {
  46433. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46434. }
  46435. //update the up vector!
  46436. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46437. };
  46438. /** @hidden */
  46439. TargetCamera.prototype._getViewMatrix = function () {
  46440. if (this.lockedTarget) {
  46441. this.setTarget(this._getLockedTargetPosition());
  46442. }
  46443. // Compute
  46444. this._updateCameraRotationMatrix();
  46445. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46446. // Computing target and final matrix
  46447. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46448. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46449. return this._viewMatrix;
  46450. };
  46451. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46452. if (this.parent) {
  46453. var parentWorldMatrix = this.parent.getWorldMatrix();
  46454. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46455. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46456. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46457. this._markSyncedWithParent();
  46458. }
  46459. else {
  46460. this._globalPosition.copyFrom(position);
  46461. this._globalCurrentTarget.copyFrom(target);
  46462. this._globalCurrentUpVector.copyFrom(up);
  46463. }
  46464. if (this.getScene().useRightHandedSystem) {
  46465. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46466. }
  46467. else {
  46468. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46469. }
  46470. };
  46471. /**
  46472. * @override
  46473. * Override Camera.createRigCamera
  46474. */
  46475. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46476. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46477. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46478. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46479. if (!this.rotationQuaternion) {
  46480. this.rotationQuaternion = new BABYLON.Quaternion();
  46481. }
  46482. rigCamera._cameraRigParams = {};
  46483. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46484. }
  46485. return rigCamera;
  46486. }
  46487. return null;
  46488. };
  46489. /**
  46490. * @hidden
  46491. * @override
  46492. * Override Camera._updateRigCameras
  46493. */
  46494. TargetCamera.prototype._updateRigCameras = function () {
  46495. var camLeft = this._rigCameras[0];
  46496. var camRight = this._rigCameras[1];
  46497. switch (this.cameraRigMode) {
  46498. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46499. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46500. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46501. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46502. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46503. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46504. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46505. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46506. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46507. camLeft.setTarget(this.getTarget());
  46508. camRight.setTarget(this.getTarget());
  46509. break;
  46510. case BABYLON.Camera.RIG_MODE_VR:
  46511. if (camLeft.rotationQuaternion) {
  46512. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46513. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46514. }
  46515. else {
  46516. camLeft.rotation.copyFrom(this.rotation);
  46517. camRight.rotation.copyFrom(this.rotation);
  46518. }
  46519. camLeft.position.copyFrom(this.position);
  46520. camRight.position.copyFrom(this.position);
  46521. break;
  46522. }
  46523. _super.prototype._updateRigCameras.call(this);
  46524. };
  46525. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46526. if (!this._rigCamTransformMatrix) {
  46527. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46528. }
  46529. var target = this.getTarget();
  46530. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46531. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46532. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46533. };
  46534. TargetCamera.prototype.getClassName = function () {
  46535. return "TargetCamera";
  46536. };
  46537. __decorate([
  46538. BABYLON.serializeAsVector3()
  46539. ], TargetCamera.prototype, "rotation", void 0);
  46540. __decorate([
  46541. BABYLON.serialize()
  46542. ], TargetCamera.prototype, "speed", void 0);
  46543. __decorate([
  46544. BABYLON.serializeAsMeshReference("lockedTargetId")
  46545. ], TargetCamera.prototype, "lockedTarget", void 0);
  46546. return TargetCamera;
  46547. }(BABYLON.Camera));
  46548. BABYLON.TargetCamera = TargetCamera;
  46549. })(BABYLON || (BABYLON = {}));
  46550. //# sourceMappingURL=babylon.targetCamera.js.map
  46551. var BABYLON;
  46552. (function (BABYLON) {
  46553. var FreeCameraMouseInput = /** @class */ (function () {
  46554. function FreeCameraMouseInput(touchEnabled) {
  46555. if (touchEnabled === void 0) { touchEnabled = true; }
  46556. this.touchEnabled = touchEnabled;
  46557. this.buttons = [0, 1, 2];
  46558. this.angularSensibility = 2000.0;
  46559. this.previousPosition = null;
  46560. }
  46561. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46562. var _this = this;
  46563. var engine = this.camera.getEngine();
  46564. if (!this._pointerInput) {
  46565. this._pointerInput = function (p, s) {
  46566. var evt = p.event;
  46567. if (engine.isInVRExclusivePointerMode) {
  46568. return;
  46569. }
  46570. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46571. return;
  46572. }
  46573. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46574. return;
  46575. }
  46576. var srcElement = (evt.srcElement || evt.target);
  46577. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46578. try {
  46579. srcElement.setPointerCapture(evt.pointerId);
  46580. }
  46581. catch (e) {
  46582. //Nothing to do with the error. Execution will continue.
  46583. }
  46584. _this.previousPosition = {
  46585. x: evt.clientX,
  46586. y: evt.clientY
  46587. };
  46588. if (!noPreventDefault) {
  46589. evt.preventDefault();
  46590. element.focus();
  46591. }
  46592. }
  46593. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46594. try {
  46595. srcElement.releasePointerCapture(evt.pointerId);
  46596. }
  46597. catch (e) {
  46598. //Nothing to do with the error.
  46599. }
  46600. _this.previousPosition = null;
  46601. if (!noPreventDefault) {
  46602. evt.preventDefault();
  46603. }
  46604. }
  46605. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46606. if (!_this.previousPosition || engine.isPointerLock) {
  46607. return;
  46608. }
  46609. var offsetX = evt.clientX - _this.previousPosition.x;
  46610. if (_this.camera.getScene().useRightHandedSystem)
  46611. offsetX *= -1;
  46612. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46613. offsetX *= -1;
  46614. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46615. var offsetY = evt.clientY - _this.previousPosition.y;
  46616. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46617. _this.previousPosition = {
  46618. x: evt.clientX,
  46619. y: evt.clientY
  46620. };
  46621. if (!noPreventDefault) {
  46622. evt.preventDefault();
  46623. }
  46624. }
  46625. };
  46626. }
  46627. this._onMouseMove = function (evt) {
  46628. if (!engine.isPointerLock) {
  46629. return;
  46630. }
  46631. if (engine.isInVRExclusivePointerMode) {
  46632. return;
  46633. }
  46634. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46635. if (_this.camera.getScene().useRightHandedSystem)
  46636. offsetX *= -1;
  46637. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46638. offsetX *= -1;
  46639. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46640. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46641. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46642. _this.previousPosition = null;
  46643. if (!noPreventDefault) {
  46644. evt.preventDefault();
  46645. }
  46646. };
  46647. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46648. element.addEventListener("mousemove", this._onMouseMove, false);
  46649. };
  46650. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46651. if (this._observer && element) {
  46652. this.camera.getScene().onPointerObservable.remove(this._observer);
  46653. if (this._onMouseMove) {
  46654. element.removeEventListener("mousemove", this._onMouseMove);
  46655. }
  46656. this._observer = null;
  46657. this._onMouseMove = null;
  46658. this.previousPosition = null;
  46659. }
  46660. };
  46661. FreeCameraMouseInput.prototype.getClassName = function () {
  46662. return "FreeCameraMouseInput";
  46663. };
  46664. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46665. return "mouse";
  46666. };
  46667. __decorate([
  46668. BABYLON.serialize()
  46669. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46670. __decorate([
  46671. BABYLON.serialize()
  46672. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46673. return FreeCameraMouseInput;
  46674. }());
  46675. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46676. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46677. })(BABYLON || (BABYLON = {}));
  46678. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46679. var BABYLON;
  46680. (function (BABYLON) {
  46681. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46682. function FreeCameraKeyboardMoveInput() {
  46683. this._keys = new Array();
  46684. this.keysUp = [38];
  46685. this.keysDown = [40];
  46686. this.keysLeft = [37];
  46687. this.keysRight = [39];
  46688. }
  46689. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46690. var _this = this;
  46691. if (this._onCanvasBlurObserver) {
  46692. return;
  46693. }
  46694. this._scene = this.camera.getScene();
  46695. this._engine = this._scene.getEngine();
  46696. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46697. _this._keys = [];
  46698. });
  46699. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46700. var evt = info.event;
  46701. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46702. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46703. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46704. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46705. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46706. var index = _this._keys.indexOf(evt.keyCode);
  46707. if (index === -1) {
  46708. _this._keys.push(evt.keyCode);
  46709. }
  46710. if (!noPreventDefault) {
  46711. evt.preventDefault();
  46712. }
  46713. }
  46714. }
  46715. else {
  46716. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46717. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46718. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46719. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46720. var index = _this._keys.indexOf(evt.keyCode);
  46721. if (index >= 0) {
  46722. _this._keys.splice(index, 1);
  46723. }
  46724. if (!noPreventDefault) {
  46725. evt.preventDefault();
  46726. }
  46727. }
  46728. }
  46729. });
  46730. };
  46731. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46732. if (this._scene) {
  46733. if (this._onKeyboardObserver) {
  46734. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46735. }
  46736. if (this._onCanvasBlurObserver) {
  46737. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46738. }
  46739. this._onKeyboardObserver = null;
  46740. this._onCanvasBlurObserver = null;
  46741. }
  46742. this._keys = [];
  46743. };
  46744. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46745. if (this._onKeyboardObserver) {
  46746. var camera = this.camera;
  46747. // Keyboard
  46748. for (var index = 0; index < this._keys.length; index++) {
  46749. var keyCode = this._keys[index];
  46750. var speed = camera._computeLocalCameraSpeed();
  46751. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46752. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46753. }
  46754. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46755. camera._localDirection.copyFromFloats(0, 0, speed);
  46756. }
  46757. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46758. camera._localDirection.copyFromFloats(speed, 0, 0);
  46759. }
  46760. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46761. camera._localDirection.copyFromFloats(0, 0, -speed);
  46762. }
  46763. if (camera.getScene().useRightHandedSystem) {
  46764. camera._localDirection.z *= -1;
  46765. }
  46766. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46767. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46768. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46769. }
  46770. }
  46771. };
  46772. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46773. return "FreeCameraKeyboardMoveInput";
  46774. };
  46775. /** @hidden */
  46776. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46777. this._keys = [];
  46778. };
  46779. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46780. return "keyboard";
  46781. };
  46782. __decorate([
  46783. BABYLON.serialize()
  46784. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46785. __decorate([
  46786. BABYLON.serialize()
  46787. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46788. __decorate([
  46789. BABYLON.serialize()
  46790. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46791. __decorate([
  46792. BABYLON.serialize()
  46793. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46794. return FreeCameraKeyboardMoveInput;
  46795. }());
  46796. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46797. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46798. })(BABYLON || (BABYLON = {}));
  46799. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46800. var BABYLON;
  46801. (function (BABYLON) {
  46802. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46803. __extends(FreeCameraInputsManager, _super);
  46804. function FreeCameraInputsManager(camera) {
  46805. return _super.call(this, camera) || this;
  46806. }
  46807. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46808. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46809. return this;
  46810. };
  46811. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46812. if (touchEnabled === void 0) { touchEnabled = true; }
  46813. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46814. return this;
  46815. };
  46816. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46817. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46818. return this;
  46819. };
  46820. FreeCameraInputsManager.prototype.addTouch = function () {
  46821. this.add(new BABYLON.FreeCameraTouchInput());
  46822. return this;
  46823. };
  46824. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46825. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46826. return this;
  46827. };
  46828. return FreeCameraInputsManager;
  46829. }(BABYLON.CameraInputsManager));
  46830. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46831. })(BABYLON || (BABYLON = {}));
  46832. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46833. var BABYLON;
  46834. (function (BABYLON) {
  46835. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46836. // Forcing to use the Universal camera
  46837. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46838. });
  46839. var FreeCamera = /** @class */ (function (_super) {
  46840. __extends(FreeCamera, _super);
  46841. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46842. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46843. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46844. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46845. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46846. _this.checkCollisions = false;
  46847. _this.applyGravity = false;
  46848. _this._needMoveForGravity = false;
  46849. _this._oldPosition = BABYLON.Vector3.Zero();
  46850. _this._diffPosition = BABYLON.Vector3.Zero();
  46851. _this._newPosition = BABYLON.Vector3.Zero();
  46852. // Collisions
  46853. _this._collisionMask = -1;
  46854. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46855. if (collidedMesh === void 0) { collidedMesh = null; }
  46856. //TODO move this to the collision coordinator!
  46857. if (_this.getScene().workerCollisions)
  46858. newPosition.multiplyInPlace(_this._collider._radius);
  46859. var updatePosition = function (newPos) {
  46860. _this._newPosition.copyFrom(newPos);
  46861. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46862. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46863. _this.position.addInPlace(_this._diffPosition);
  46864. if (_this.onCollide && collidedMesh) {
  46865. _this.onCollide(collidedMesh);
  46866. }
  46867. }
  46868. };
  46869. updatePosition(newPosition);
  46870. };
  46871. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46872. _this.inputs.addKeyboard().addMouse();
  46873. return _this;
  46874. }
  46875. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46876. //-- begin properties for backward compatibility for inputs
  46877. /**
  46878. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46879. * Higher values reduce sensitivity.
  46880. */
  46881. get: function () {
  46882. var mouse = this.inputs.attached["mouse"];
  46883. if (mouse)
  46884. return mouse.angularSensibility;
  46885. return 0;
  46886. },
  46887. /**
  46888. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46889. * Higher values reduce sensitivity.
  46890. */
  46891. set: function (value) {
  46892. var mouse = this.inputs.attached["mouse"];
  46893. if (mouse)
  46894. mouse.angularSensibility = value;
  46895. },
  46896. enumerable: true,
  46897. configurable: true
  46898. });
  46899. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46900. get: function () {
  46901. var keyboard = this.inputs.attached["keyboard"];
  46902. if (keyboard)
  46903. return keyboard.keysUp;
  46904. return [];
  46905. },
  46906. set: function (value) {
  46907. var keyboard = this.inputs.attached["keyboard"];
  46908. if (keyboard)
  46909. keyboard.keysUp = value;
  46910. },
  46911. enumerable: true,
  46912. configurable: true
  46913. });
  46914. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46915. get: function () {
  46916. var keyboard = this.inputs.attached["keyboard"];
  46917. if (keyboard)
  46918. return keyboard.keysDown;
  46919. return [];
  46920. },
  46921. set: function (value) {
  46922. var keyboard = this.inputs.attached["keyboard"];
  46923. if (keyboard)
  46924. keyboard.keysDown = value;
  46925. },
  46926. enumerable: true,
  46927. configurable: true
  46928. });
  46929. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46930. get: function () {
  46931. var keyboard = this.inputs.attached["keyboard"];
  46932. if (keyboard)
  46933. return keyboard.keysLeft;
  46934. return [];
  46935. },
  46936. set: function (value) {
  46937. var keyboard = this.inputs.attached["keyboard"];
  46938. if (keyboard)
  46939. keyboard.keysLeft = value;
  46940. },
  46941. enumerable: true,
  46942. configurable: true
  46943. });
  46944. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46945. get: function () {
  46946. var keyboard = this.inputs.attached["keyboard"];
  46947. if (keyboard)
  46948. return keyboard.keysRight;
  46949. return [];
  46950. },
  46951. set: function (value) {
  46952. var keyboard = this.inputs.attached["keyboard"];
  46953. if (keyboard)
  46954. keyboard.keysRight = value;
  46955. },
  46956. enumerable: true,
  46957. configurable: true
  46958. });
  46959. // Controls
  46960. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46961. this.inputs.attachElement(element, noPreventDefault);
  46962. };
  46963. FreeCamera.prototype.detachControl = function (element) {
  46964. this.inputs.detachElement(element);
  46965. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46966. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46967. };
  46968. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46969. get: function () {
  46970. return this._collisionMask;
  46971. },
  46972. set: function (mask) {
  46973. this._collisionMask = !isNaN(mask) ? mask : -1;
  46974. },
  46975. enumerable: true,
  46976. configurable: true
  46977. });
  46978. /** @hidden */
  46979. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46980. var globalPosition;
  46981. if (this.parent) {
  46982. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46983. }
  46984. else {
  46985. globalPosition = this.position;
  46986. }
  46987. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46988. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46989. if (!this._collider) {
  46990. this._collider = new BABYLON.Collider();
  46991. }
  46992. this._collider._radius = this.ellipsoid;
  46993. this._collider.collisionMask = this._collisionMask;
  46994. //no need for clone, as long as gravity is not on.
  46995. var actualDisplacement = displacement;
  46996. //add gravity to the direction to prevent the dual-collision checking
  46997. if (this.applyGravity) {
  46998. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46999. actualDisplacement = displacement.add(this.getScene().gravity);
  47000. }
  47001. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47002. };
  47003. /** @hidden */
  47004. FreeCamera.prototype._checkInputs = function () {
  47005. if (!this._localDirection) {
  47006. this._localDirection = BABYLON.Vector3.Zero();
  47007. this._transformedDirection = BABYLON.Vector3.Zero();
  47008. }
  47009. this.inputs.checkInputs();
  47010. _super.prototype._checkInputs.call(this);
  47011. };
  47012. /** @hidden */
  47013. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47014. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47015. };
  47016. /** @hidden */
  47017. FreeCamera.prototype._updatePosition = function () {
  47018. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47019. this._collideWithWorld(this.cameraDirection);
  47020. }
  47021. else {
  47022. _super.prototype._updatePosition.call(this);
  47023. }
  47024. };
  47025. FreeCamera.prototype.dispose = function () {
  47026. this.inputs.clear();
  47027. _super.prototype.dispose.call(this);
  47028. };
  47029. FreeCamera.prototype.getClassName = function () {
  47030. return "FreeCamera";
  47031. };
  47032. __decorate([
  47033. BABYLON.serializeAsVector3()
  47034. ], FreeCamera.prototype, "ellipsoid", void 0);
  47035. __decorate([
  47036. BABYLON.serializeAsVector3()
  47037. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47038. __decorate([
  47039. BABYLON.serialize()
  47040. ], FreeCamera.prototype, "checkCollisions", void 0);
  47041. __decorate([
  47042. BABYLON.serialize()
  47043. ], FreeCamera.prototype, "applyGravity", void 0);
  47044. return FreeCamera;
  47045. }(BABYLON.TargetCamera));
  47046. BABYLON.FreeCamera = FreeCamera;
  47047. })(BABYLON || (BABYLON = {}));
  47048. //# sourceMappingURL=babylon.freeCamera.js.map
  47049. var BABYLON;
  47050. (function (BABYLON) {
  47051. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47052. function ArcRotateCameraKeyboardMoveInput() {
  47053. this._keys = new Array();
  47054. this.keysUp = [38];
  47055. this.keysDown = [40];
  47056. this.keysLeft = [37];
  47057. this.keysRight = [39];
  47058. this.keysReset = [220];
  47059. this.panningSensibility = 50.0;
  47060. this.zoomingSensibility = 25.0;
  47061. this.useAltToZoom = true;
  47062. }
  47063. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47064. var _this = this;
  47065. if (this._onCanvasBlurObserver) {
  47066. return;
  47067. }
  47068. this._scene = this.camera.getScene();
  47069. this._engine = this._scene.getEngine();
  47070. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47071. _this._keys = [];
  47072. });
  47073. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47074. var evt = info.event;
  47075. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47076. _this._ctrlPressed = evt.ctrlKey;
  47077. _this._altPressed = evt.altKey;
  47078. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47079. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47080. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47081. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47082. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47083. var index = _this._keys.indexOf(evt.keyCode);
  47084. if (index === -1) {
  47085. _this._keys.push(evt.keyCode);
  47086. }
  47087. if (evt.preventDefault) {
  47088. if (!noPreventDefault) {
  47089. evt.preventDefault();
  47090. }
  47091. }
  47092. }
  47093. }
  47094. else {
  47095. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47096. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47097. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47098. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47099. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47100. var index = _this._keys.indexOf(evt.keyCode);
  47101. if (index >= 0) {
  47102. _this._keys.splice(index, 1);
  47103. }
  47104. if (evt.preventDefault) {
  47105. if (!noPreventDefault) {
  47106. evt.preventDefault();
  47107. }
  47108. }
  47109. }
  47110. }
  47111. });
  47112. };
  47113. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47114. if (this._scene) {
  47115. if (this._onKeyboardObserver) {
  47116. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47117. }
  47118. if (this._onCanvasBlurObserver) {
  47119. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47120. }
  47121. this._onKeyboardObserver = null;
  47122. this._onCanvasBlurObserver = null;
  47123. }
  47124. this._keys = [];
  47125. };
  47126. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47127. if (this._onKeyboardObserver) {
  47128. var camera = this.camera;
  47129. for (var index = 0; index < this._keys.length; index++) {
  47130. var keyCode = this._keys[index];
  47131. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47132. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47133. camera.inertialPanningX -= 1 / this.panningSensibility;
  47134. }
  47135. else {
  47136. camera.inertialAlphaOffset -= 0.01;
  47137. }
  47138. }
  47139. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47140. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47141. camera.inertialPanningY += 1 / this.panningSensibility;
  47142. }
  47143. else if (this._altPressed && this.useAltToZoom) {
  47144. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47145. }
  47146. else {
  47147. camera.inertialBetaOffset -= 0.01;
  47148. }
  47149. }
  47150. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47151. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47152. camera.inertialPanningX += 1 / this.panningSensibility;
  47153. }
  47154. else {
  47155. camera.inertialAlphaOffset += 0.01;
  47156. }
  47157. }
  47158. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47159. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47160. camera.inertialPanningY -= 1 / this.panningSensibility;
  47161. }
  47162. else if (this._altPressed && this.useAltToZoom) {
  47163. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47164. }
  47165. else {
  47166. camera.inertialBetaOffset += 0.01;
  47167. }
  47168. }
  47169. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47170. camera.restoreState();
  47171. }
  47172. }
  47173. }
  47174. };
  47175. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47176. return "ArcRotateCameraKeyboardMoveInput";
  47177. };
  47178. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47179. return "keyboard";
  47180. };
  47181. __decorate([
  47182. BABYLON.serialize()
  47183. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47184. __decorate([
  47185. BABYLON.serialize()
  47186. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47187. __decorate([
  47188. BABYLON.serialize()
  47189. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47190. __decorate([
  47191. BABYLON.serialize()
  47192. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47193. __decorate([
  47194. BABYLON.serialize()
  47195. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47196. __decorate([
  47197. BABYLON.serialize()
  47198. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47199. __decorate([
  47200. BABYLON.serialize()
  47201. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47202. __decorate([
  47203. BABYLON.serialize()
  47204. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47205. return ArcRotateCameraKeyboardMoveInput;
  47206. }());
  47207. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47208. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47209. })(BABYLON || (BABYLON = {}));
  47210. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47211. var BABYLON;
  47212. (function (BABYLON) {
  47213. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47214. function ArcRotateCameraMouseWheelInput() {
  47215. this.wheelPrecision = 3.0;
  47216. /**
  47217. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47218. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47219. */
  47220. this.wheelDeltaPercentage = 0;
  47221. }
  47222. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47223. var _this = this;
  47224. this._wheel = function (p, s) {
  47225. //sanity check - this should be a PointerWheel event.
  47226. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47227. return;
  47228. var event = p.event;
  47229. var delta = 0;
  47230. if (event.wheelDelta) {
  47231. if (_this.wheelDeltaPercentage) {
  47232. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47233. if (event.wheelDelta > 0) {
  47234. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47235. }
  47236. else {
  47237. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47238. }
  47239. }
  47240. else {
  47241. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47242. }
  47243. }
  47244. else if (event.detail) {
  47245. delta = -event.detail / _this.wheelPrecision;
  47246. }
  47247. if (delta)
  47248. _this.camera.inertialRadiusOffset += delta;
  47249. if (event.preventDefault) {
  47250. if (!noPreventDefault) {
  47251. event.preventDefault();
  47252. }
  47253. }
  47254. };
  47255. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47256. };
  47257. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47258. if (this._observer && element) {
  47259. this.camera.getScene().onPointerObservable.remove(this._observer);
  47260. this._observer = null;
  47261. this._wheel = null;
  47262. }
  47263. };
  47264. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47265. return "ArcRotateCameraMouseWheelInput";
  47266. };
  47267. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47268. return "mousewheel";
  47269. };
  47270. __decorate([
  47271. BABYLON.serialize()
  47272. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47273. __decorate([
  47274. BABYLON.serialize()
  47275. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47276. return ArcRotateCameraMouseWheelInput;
  47277. }());
  47278. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47279. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47280. })(BABYLON || (BABYLON = {}));
  47281. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47282. var BABYLON;
  47283. (function (BABYLON) {
  47284. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47285. function ArcRotateCameraPointersInput() {
  47286. this.buttons = [0, 1, 2];
  47287. this.angularSensibilityX = 1000.0;
  47288. this.angularSensibilityY = 1000.0;
  47289. this.pinchPrecision = 12.0;
  47290. /**
  47291. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47292. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47293. */
  47294. this.pinchDeltaPercentage = 0;
  47295. this.panningSensibility = 1000.0;
  47296. this.multiTouchPanning = true;
  47297. this.multiTouchPanAndZoom = true;
  47298. this._isPanClick = false;
  47299. this.pinchInwards = true;
  47300. }
  47301. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47302. var _this = this;
  47303. var engine = this.camera.getEngine();
  47304. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47305. var pointA = null;
  47306. var pointB = null;
  47307. var previousPinchSquaredDistance = 0;
  47308. var initialDistance = 0;
  47309. var twoFingerActivityCount = 0;
  47310. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47311. this._pointerInput = function (p, s) {
  47312. var evt = p.event;
  47313. var isTouch = p.event.pointerType === "touch";
  47314. if (engine.isInVRExclusivePointerMode) {
  47315. return;
  47316. }
  47317. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47318. return;
  47319. }
  47320. var srcElement = (evt.srcElement || evt.target);
  47321. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47322. try {
  47323. srcElement.setPointerCapture(evt.pointerId);
  47324. }
  47325. catch (e) {
  47326. //Nothing to do with the error. Execution will continue.
  47327. }
  47328. // Manage panning with pan button click
  47329. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47330. // manage pointers
  47331. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47332. if (pointA === null) {
  47333. pointA = cacheSoloPointer;
  47334. }
  47335. else if (pointB === null) {
  47336. pointB = cacheSoloPointer;
  47337. }
  47338. if (!noPreventDefault) {
  47339. evt.preventDefault();
  47340. element.focus();
  47341. }
  47342. }
  47343. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47344. _this.camera.restoreState();
  47345. }
  47346. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47347. try {
  47348. srcElement.releasePointerCapture(evt.pointerId);
  47349. }
  47350. catch (e) {
  47351. //Nothing to do with the error.
  47352. }
  47353. cacheSoloPointer = null;
  47354. previousPinchSquaredDistance = 0;
  47355. previousMultiTouchPanPosition.isPaning = false;
  47356. previousMultiTouchPanPosition.isPinching = false;
  47357. twoFingerActivityCount = 0;
  47358. initialDistance = 0;
  47359. if (!isTouch) {
  47360. pointB = null; // Mouse and pen are mono pointer
  47361. }
  47362. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47363. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47364. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47365. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47366. if (engine._badOS) {
  47367. pointA = pointB = null;
  47368. }
  47369. else {
  47370. //only remove the impacted pointer in case of multitouch allowing on most
  47371. //platforms switching from rotate to zoom and pan seamlessly.
  47372. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47373. pointA = pointB;
  47374. pointB = null;
  47375. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47376. }
  47377. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47378. pointB = null;
  47379. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47380. }
  47381. else {
  47382. pointA = pointB = null;
  47383. }
  47384. }
  47385. if (!noPreventDefault) {
  47386. evt.preventDefault();
  47387. }
  47388. }
  47389. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47390. if (!noPreventDefault) {
  47391. evt.preventDefault();
  47392. }
  47393. // One button down
  47394. if (pointA && pointB === null && cacheSoloPointer) {
  47395. if (_this.panningSensibility !== 0 &&
  47396. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47397. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47398. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47399. }
  47400. else {
  47401. var offsetX = evt.clientX - cacheSoloPointer.x;
  47402. var offsetY = evt.clientY - cacheSoloPointer.y;
  47403. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47404. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47405. }
  47406. cacheSoloPointer.x = evt.clientX;
  47407. cacheSoloPointer.y = evt.clientY;
  47408. }
  47409. // Two buttons down: pinch/pan
  47410. else if (pointA && pointB) {
  47411. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47412. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47413. ed.x = evt.clientX;
  47414. ed.y = evt.clientY;
  47415. var direction = _this.pinchInwards ? 1 : -1;
  47416. var distX = pointA.x - pointB.x;
  47417. var distY = pointA.y - pointB.y;
  47418. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47419. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47420. if (previousPinchSquaredDistance === 0) {
  47421. initialDistance = pinchDistance;
  47422. previousPinchSquaredDistance = pinchSquaredDistance;
  47423. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47424. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47425. return;
  47426. }
  47427. if (_this.multiTouchPanAndZoom) {
  47428. if (_this.pinchDeltaPercentage) {
  47429. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47430. }
  47431. else {
  47432. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47433. (_this.pinchPrecision *
  47434. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47435. direction);
  47436. }
  47437. if (_this.panningSensibility !== 0) {
  47438. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47439. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47440. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47441. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47442. previousMultiTouchPanPosition.x = pointersCenterX;
  47443. previousMultiTouchPanPosition.y = pointersCenterY;
  47444. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47445. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47446. }
  47447. }
  47448. else {
  47449. twoFingerActivityCount++;
  47450. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47451. if (_this.pinchDeltaPercentage) {
  47452. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47453. }
  47454. else {
  47455. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47456. (_this.pinchPrecision *
  47457. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47458. direction);
  47459. }
  47460. previousMultiTouchPanPosition.isPaning = false;
  47461. previousMultiTouchPanPosition.isPinching = true;
  47462. }
  47463. else {
  47464. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47465. if (!previousMultiTouchPanPosition.isPaning) {
  47466. previousMultiTouchPanPosition.isPaning = true;
  47467. previousMultiTouchPanPosition.isPinching = false;
  47468. previousMultiTouchPanPosition.x = ed.x;
  47469. previousMultiTouchPanPosition.y = ed.y;
  47470. return;
  47471. }
  47472. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47473. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47474. }
  47475. }
  47476. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47477. previousMultiTouchPanPosition.x = ed.x;
  47478. previousMultiTouchPanPosition.y = ed.y;
  47479. }
  47480. }
  47481. previousPinchSquaredDistance = pinchSquaredDistance;
  47482. }
  47483. }
  47484. };
  47485. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47486. this._onContextMenu = function (evt) {
  47487. evt.preventDefault();
  47488. };
  47489. if (!this.camera._useCtrlForPanning) {
  47490. element.addEventListener("contextmenu", this._onContextMenu, false);
  47491. }
  47492. this._onLostFocus = function () {
  47493. //this._keys = [];
  47494. pointA = pointB = null;
  47495. previousPinchSquaredDistance = 0;
  47496. previousMultiTouchPanPosition.isPaning = false;
  47497. previousMultiTouchPanPosition.isPinching = false;
  47498. twoFingerActivityCount = 0;
  47499. cacheSoloPointer = null;
  47500. initialDistance = 0;
  47501. };
  47502. this._onMouseMove = function (evt) {
  47503. if (!engine.isPointerLock) {
  47504. return;
  47505. }
  47506. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47507. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47508. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47509. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47510. if (!noPreventDefault) {
  47511. evt.preventDefault();
  47512. }
  47513. };
  47514. this._onGestureStart = function (e) {
  47515. if (window.MSGesture === undefined) {
  47516. return;
  47517. }
  47518. if (!_this._MSGestureHandler) {
  47519. _this._MSGestureHandler = new MSGesture();
  47520. _this._MSGestureHandler.target = element;
  47521. }
  47522. _this._MSGestureHandler.addPointer(e.pointerId);
  47523. };
  47524. this._onGesture = function (e) {
  47525. _this.camera.radius *= e.scale;
  47526. if (e.preventDefault) {
  47527. if (!noPreventDefault) {
  47528. e.stopPropagation();
  47529. e.preventDefault();
  47530. }
  47531. }
  47532. };
  47533. element.addEventListener("mousemove", this._onMouseMove, false);
  47534. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47535. element.addEventListener("MSGestureChange", this._onGesture, false);
  47536. BABYLON.Tools.RegisterTopRootEvents([
  47537. { name: "blur", handler: this._onLostFocus }
  47538. ]);
  47539. };
  47540. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47541. if (this._onLostFocus) {
  47542. BABYLON.Tools.UnregisterTopRootEvents([
  47543. { name: "blur", handler: this._onLostFocus }
  47544. ]);
  47545. }
  47546. if (element && this._observer) {
  47547. this.camera.getScene().onPointerObservable.remove(this._observer);
  47548. this._observer = null;
  47549. if (this._onContextMenu) {
  47550. element.removeEventListener("contextmenu", this._onContextMenu);
  47551. }
  47552. if (this._onMouseMove) {
  47553. element.removeEventListener("mousemove", this._onMouseMove);
  47554. }
  47555. if (this._onGestureStart) {
  47556. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47557. }
  47558. if (this._onGesture) {
  47559. element.removeEventListener("MSGestureChange", this._onGesture);
  47560. }
  47561. this._isPanClick = false;
  47562. this.pinchInwards = true;
  47563. this._onMouseMove = null;
  47564. this._onGestureStart = null;
  47565. this._onGesture = null;
  47566. this._MSGestureHandler = null;
  47567. this._onLostFocus = null;
  47568. this._onContextMenu = null;
  47569. }
  47570. };
  47571. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47572. return "ArcRotateCameraPointersInput";
  47573. };
  47574. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47575. return "pointers";
  47576. };
  47577. __decorate([
  47578. BABYLON.serialize()
  47579. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47580. __decorate([
  47581. BABYLON.serialize()
  47582. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47583. __decorate([
  47584. BABYLON.serialize()
  47585. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47586. __decorate([
  47587. BABYLON.serialize()
  47588. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47589. __decorate([
  47590. BABYLON.serialize()
  47591. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47592. __decorate([
  47593. BABYLON.serialize()
  47594. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47595. __decorate([
  47596. BABYLON.serialize()
  47597. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47598. __decorate([
  47599. BABYLON.serialize()
  47600. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47601. return ArcRotateCameraPointersInput;
  47602. }());
  47603. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47604. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47605. })(BABYLON || (BABYLON = {}));
  47606. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47607. var BABYLON;
  47608. (function (BABYLON) {
  47609. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47610. __extends(ArcRotateCameraInputsManager, _super);
  47611. function ArcRotateCameraInputsManager(camera) {
  47612. return _super.call(this, camera) || this;
  47613. }
  47614. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47615. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47616. return this;
  47617. };
  47618. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47619. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47620. return this;
  47621. };
  47622. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47623. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47624. return this;
  47625. };
  47626. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47627. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47628. return this;
  47629. };
  47630. return ArcRotateCameraInputsManager;
  47631. }(BABYLON.CameraInputsManager));
  47632. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47633. })(BABYLON || (BABYLON = {}));
  47634. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47635. 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#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\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#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \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"};
  47636. var BABYLON;
  47637. (function (BABYLON) {
  47638. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47639. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47640. });
  47641. var ArcRotateCamera = /** @class */ (function (_super) {
  47642. __extends(ArcRotateCamera, _super);
  47643. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47644. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47645. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47646. _this.inertialAlphaOffset = 0;
  47647. _this.inertialBetaOffset = 0;
  47648. _this.inertialRadiusOffset = 0;
  47649. _this.lowerAlphaLimit = null;
  47650. _this.upperAlphaLimit = null;
  47651. _this.lowerBetaLimit = 0.01;
  47652. _this.upperBetaLimit = Math.PI;
  47653. _this.lowerRadiusLimit = null;
  47654. _this.upperRadiusLimit = null;
  47655. _this.inertialPanningX = 0;
  47656. _this.inertialPanningY = 0;
  47657. _this.pinchToPanMaxDistance = 20;
  47658. _this.panningDistanceLimit = null;
  47659. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47660. _this.panningInertia = 0.9;
  47661. //-- end properties for backward compatibility for inputs
  47662. _this.zoomOnFactor = 1;
  47663. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47664. _this.allowUpsideDown = true;
  47665. /** @hidden */
  47666. _this._viewMatrix = new BABYLON.Matrix();
  47667. // Panning
  47668. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47669. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47670. _this.checkCollisions = false;
  47671. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47672. _this._previousPosition = BABYLON.Vector3.Zero();
  47673. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47674. _this._newPosition = BABYLON.Vector3.Zero();
  47675. _this._computationVector = BABYLON.Vector3.Zero();
  47676. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47677. if (collidedMesh === void 0) { collidedMesh = null; }
  47678. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47679. newPosition.multiplyInPlace(_this._collider._radius);
  47680. }
  47681. if (!collidedMesh) {
  47682. _this._previousPosition.copyFrom(_this.position);
  47683. }
  47684. else {
  47685. _this.setPosition(newPosition);
  47686. if (_this.onCollide) {
  47687. _this.onCollide(collidedMesh);
  47688. }
  47689. }
  47690. // Recompute because of constraints
  47691. var cosa = Math.cos(_this.alpha);
  47692. var sina = Math.sin(_this.alpha);
  47693. var cosb = Math.cos(_this.beta);
  47694. var sinb = Math.sin(_this.beta);
  47695. if (sinb === 0) {
  47696. sinb = 0.0001;
  47697. }
  47698. var target = _this._getTargetPosition();
  47699. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47700. target.addToRef(_this._computationVector, _this._newPosition);
  47701. _this.position.copyFrom(_this._newPosition);
  47702. var up = _this.upVector;
  47703. if (_this.allowUpsideDown && _this.beta < 0) {
  47704. up = up.clone();
  47705. up = up.negate();
  47706. }
  47707. _this._computeViewMatrix(_this.position, target, up);
  47708. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47709. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47710. _this._collisionTriggered = false;
  47711. };
  47712. _this._target = BABYLON.Vector3.Zero();
  47713. if (target) {
  47714. _this.setTarget(target);
  47715. }
  47716. _this.alpha = alpha;
  47717. _this.beta = beta;
  47718. _this.radius = radius;
  47719. _this.getViewMatrix();
  47720. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47721. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47722. return _this;
  47723. }
  47724. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47725. get: function () {
  47726. return this._target;
  47727. },
  47728. set: function (value) {
  47729. this.setTarget(value);
  47730. },
  47731. enumerable: true,
  47732. configurable: true
  47733. });
  47734. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47735. //-- begin properties for backward compatibility for inputs
  47736. get: function () {
  47737. var pointers = this.inputs.attached["pointers"];
  47738. if (pointers)
  47739. return pointers.angularSensibilityX;
  47740. return 0;
  47741. },
  47742. set: function (value) {
  47743. var pointers = this.inputs.attached["pointers"];
  47744. if (pointers) {
  47745. pointers.angularSensibilityX = value;
  47746. }
  47747. },
  47748. enumerable: true,
  47749. configurable: true
  47750. });
  47751. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47752. get: function () {
  47753. var pointers = this.inputs.attached["pointers"];
  47754. if (pointers)
  47755. return pointers.angularSensibilityY;
  47756. return 0;
  47757. },
  47758. set: function (value) {
  47759. var pointers = this.inputs.attached["pointers"];
  47760. if (pointers) {
  47761. pointers.angularSensibilityY = value;
  47762. }
  47763. },
  47764. enumerable: true,
  47765. configurable: true
  47766. });
  47767. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47768. get: function () {
  47769. var pointers = this.inputs.attached["pointers"];
  47770. if (pointers)
  47771. return pointers.pinchPrecision;
  47772. return 0;
  47773. },
  47774. set: function (value) {
  47775. var pointers = this.inputs.attached["pointers"];
  47776. if (pointers) {
  47777. pointers.pinchPrecision = value;
  47778. }
  47779. },
  47780. enumerable: true,
  47781. configurable: true
  47782. });
  47783. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47784. get: function () {
  47785. var pointers = this.inputs.attached["pointers"];
  47786. if (pointers)
  47787. return pointers.pinchDeltaPercentage;
  47788. return 0;
  47789. },
  47790. set: function (value) {
  47791. var pointers = this.inputs.attached["pointers"];
  47792. if (pointers) {
  47793. pointers.pinchDeltaPercentage = value;
  47794. }
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47800. get: function () {
  47801. var pointers = this.inputs.attached["pointers"];
  47802. if (pointers)
  47803. return pointers.panningSensibility;
  47804. return 0;
  47805. },
  47806. set: function (value) {
  47807. var pointers = this.inputs.attached["pointers"];
  47808. if (pointers) {
  47809. pointers.panningSensibility = value;
  47810. }
  47811. },
  47812. enumerable: true,
  47813. configurable: true
  47814. });
  47815. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47816. get: function () {
  47817. var keyboard = this.inputs.attached["keyboard"];
  47818. if (keyboard)
  47819. return keyboard.keysUp;
  47820. return [];
  47821. },
  47822. set: function (value) {
  47823. var keyboard = this.inputs.attached["keyboard"];
  47824. if (keyboard)
  47825. keyboard.keysUp = value;
  47826. },
  47827. enumerable: true,
  47828. configurable: true
  47829. });
  47830. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47831. get: function () {
  47832. var keyboard = this.inputs.attached["keyboard"];
  47833. if (keyboard)
  47834. return keyboard.keysDown;
  47835. return [];
  47836. },
  47837. set: function (value) {
  47838. var keyboard = this.inputs.attached["keyboard"];
  47839. if (keyboard)
  47840. keyboard.keysDown = value;
  47841. },
  47842. enumerable: true,
  47843. configurable: true
  47844. });
  47845. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47846. get: function () {
  47847. var keyboard = this.inputs.attached["keyboard"];
  47848. if (keyboard)
  47849. return keyboard.keysLeft;
  47850. return [];
  47851. },
  47852. set: function (value) {
  47853. var keyboard = this.inputs.attached["keyboard"];
  47854. if (keyboard)
  47855. keyboard.keysLeft = value;
  47856. },
  47857. enumerable: true,
  47858. configurable: true
  47859. });
  47860. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47861. get: function () {
  47862. var keyboard = this.inputs.attached["keyboard"];
  47863. if (keyboard)
  47864. return keyboard.keysRight;
  47865. return [];
  47866. },
  47867. set: function (value) {
  47868. var keyboard = this.inputs.attached["keyboard"];
  47869. if (keyboard)
  47870. keyboard.keysRight = value;
  47871. },
  47872. enumerable: true,
  47873. configurable: true
  47874. });
  47875. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47876. get: function () {
  47877. var mousewheel = this.inputs.attached["mousewheel"];
  47878. if (mousewheel)
  47879. return mousewheel.wheelPrecision;
  47880. return 0;
  47881. },
  47882. set: function (value) {
  47883. var mousewheel = this.inputs.attached["mousewheel"];
  47884. if (mousewheel)
  47885. mousewheel.wheelPrecision = value;
  47886. },
  47887. enumerable: true,
  47888. configurable: true
  47889. });
  47890. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47891. get: function () {
  47892. var mousewheel = this.inputs.attached["mousewheel"];
  47893. if (mousewheel)
  47894. return mousewheel.wheelDeltaPercentage;
  47895. return 0;
  47896. },
  47897. set: function (value) {
  47898. var mousewheel = this.inputs.attached["mousewheel"];
  47899. if (mousewheel)
  47900. mousewheel.wheelDeltaPercentage = value;
  47901. },
  47902. enumerable: true,
  47903. configurable: true
  47904. });
  47905. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47906. get: function () {
  47907. return this._bouncingBehavior;
  47908. },
  47909. enumerable: true,
  47910. configurable: true
  47911. });
  47912. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47913. get: function () {
  47914. return this._bouncingBehavior != null;
  47915. },
  47916. set: function (value) {
  47917. if (value === this.useBouncingBehavior) {
  47918. return;
  47919. }
  47920. if (value) {
  47921. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47922. this.addBehavior(this._bouncingBehavior);
  47923. }
  47924. else if (this._bouncingBehavior) {
  47925. this.removeBehavior(this._bouncingBehavior);
  47926. this._bouncingBehavior = null;
  47927. }
  47928. },
  47929. enumerable: true,
  47930. configurable: true
  47931. });
  47932. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47933. get: function () {
  47934. return this._framingBehavior;
  47935. },
  47936. enumerable: true,
  47937. configurable: true
  47938. });
  47939. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47940. get: function () {
  47941. return this._framingBehavior != null;
  47942. },
  47943. set: function (value) {
  47944. if (value === this.useFramingBehavior) {
  47945. return;
  47946. }
  47947. if (value) {
  47948. this._framingBehavior = new BABYLON.FramingBehavior();
  47949. this.addBehavior(this._framingBehavior);
  47950. }
  47951. else if (this._framingBehavior) {
  47952. this.removeBehavior(this._framingBehavior);
  47953. this._framingBehavior = null;
  47954. }
  47955. },
  47956. enumerable: true,
  47957. configurable: true
  47958. });
  47959. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47960. get: function () {
  47961. return this._autoRotationBehavior;
  47962. },
  47963. enumerable: true,
  47964. configurable: true
  47965. });
  47966. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47967. get: function () {
  47968. return this._autoRotationBehavior != null;
  47969. },
  47970. set: function (value) {
  47971. if (value === this.useAutoRotationBehavior) {
  47972. return;
  47973. }
  47974. if (value) {
  47975. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47976. this.addBehavior(this._autoRotationBehavior);
  47977. }
  47978. else if (this._autoRotationBehavior) {
  47979. this.removeBehavior(this._autoRotationBehavior);
  47980. this._autoRotationBehavior = null;
  47981. }
  47982. },
  47983. enumerable: true,
  47984. configurable: true
  47985. });
  47986. // Cache
  47987. /** @hidden */
  47988. ArcRotateCamera.prototype._initCache = function () {
  47989. _super.prototype._initCache.call(this);
  47990. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47991. this._cache.alpha = undefined;
  47992. this._cache.beta = undefined;
  47993. this._cache.radius = undefined;
  47994. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47995. };
  47996. /** @hidden */
  47997. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47998. if (!ignoreParentClass) {
  47999. _super.prototype._updateCache.call(this);
  48000. }
  48001. this._cache._target.copyFrom(this._getTargetPosition());
  48002. this._cache.alpha = this.alpha;
  48003. this._cache.beta = this.beta;
  48004. this._cache.radius = this.radius;
  48005. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48006. };
  48007. ArcRotateCamera.prototype._getTargetPosition = function () {
  48008. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48009. var pos = this._targetHost.getAbsolutePosition();
  48010. if (this._targetBoundingCenter) {
  48011. pos.addToRef(this._targetBoundingCenter, this._target);
  48012. }
  48013. else {
  48014. this._target.copyFrom(pos);
  48015. }
  48016. }
  48017. var lockedTargetPosition = this._getLockedTargetPosition();
  48018. if (lockedTargetPosition) {
  48019. return lockedTargetPosition;
  48020. }
  48021. return this._target;
  48022. };
  48023. ArcRotateCamera.prototype.storeState = function () {
  48024. this._storedAlpha = this.alpha;
  48025. this._storedBeta = this.beta;
  48026. this._storedRadius = this.radius;
  48027. this._storedTarget = this._getTargetPosition().clone();
  48028. return _super.prototype.storeState.call(this);
  48029. };
  48030. /**
  48031. * @hidden
  48032. * Restored camera state. You must call storeState() first
  48033. */
  48034. ArcRotateCamera.prototype._restoreStateValues = function () {
  48035. if (!_super.prototype._restoreStateValues.call(this)) {
  48036. return false;
  48037. }
  48038. this.alpha = this._storedAlpha;
  48039. this.beta = this._storedBeta;
  48040. this.radius = this._storedRadius;
  48041. this.setTarget(this._storedTarget.clone());
  48042. this.inertialAlphaOffset = 0;
  48043. this.inertialBetaOffset = 0;
  48044. this.inertialRadiusOffset = 0;
  48045. this.inertialPanningX = 0;
  48046. this.inertialPanningY = 0;
  48047. return true;
  48048. };
  48049. // Synchronized
  48050. /** @hidden */
  48051. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48052. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48053. return false;
  48054. return this._cache._target.equals(this._getTargetPosition())
  48055. && this._cache.alpha === this.alpha
  48056. && this._cache.beta === this.beta
  48057. && this._cache.radius === this.radius
  48058. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48059. };
  48060. // Methods
  48061. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48062. var _this = this;
  48063. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48064. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48065. this._useCtrlForPanning = useCtrlForPanning;
  48066. this._panningMouseButton = panningMouseButton;
  48067. this.inputs.attachElement(element, noPreventDefault);
  48068. this._reset = function () {
  48069. _this.inertialAlphaOffset = 0;
  48070. _this.inertialBetaOffset = 0;
  48071. _this.inertialRadiusOffset = 0;
  48072. _this.inertialPanningX = 0;
  48073. _this.inertialPanningY = 0;
  48074. };
  48075. };
  48076. ArcRotateCamera.prototype.detachControl = function (element) {
  48077. this.inputs.detachElement(element);
  48078. if (this._reset) {
  48079. this._reset();
  48080. }
  48081. };
  48082. /** @hidden */
  48083. ArcRotateCamera.prototype._checkInputs = function () {
  48084. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48085. if (this._collisionTriggered) {
  48086. return;
  48087. }
  48088. this.inputs.checkInputs();
  48089. // Inertia
  48090. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48091. var inertialAlphaOffset = this.inertialAlphaOffset;
  48092. if (this.beta <= 0)
  48093. inertialAlphaOffset *= -1;
  48094. if (this.getScene().useRightHandedSystem)
  48095. inertialAlphaOffset *= -1;
  48096. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48097. inertialAlphaOffset *= -1;
  48098. this.alpha += inertialAlphaOffset;
  48099. this.beta += this.inertialBetaOffset;
  48100. this.radius -= this.inertialRadiusOffset;
  48101. this.inertialAlphaOffset *= this.inertia;
  48102. this.inertialBetaOffset *= this.inertia;
  48103. this.inertialRadiusOffset *= this.inertia;
  48104. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48105. this.inertialAlphaOffset = 0;
  48106. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48107. this.inertialBetaOffset = 0;
  48108. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48109. this.inertialRadiusOffset = 0;
  48110. }
  48111. // Panning inertia
  48112. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48113. if (!this._localDirection) {
  48114. this._localDirection = BABYLON.Vector3.Zero();
  48115. this._transformedDirection = BABYLON.Vector3.Zero();
  48116. }
  48117. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48118. this._localDirection.multiplyInPlace(this.panningAxis);
  48119. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48120. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48121. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48122. if (!this.panningAxis.y) {
  48123. this._transformedDirection.y = 0;
  48124. }
  48125. if (!this._targetHost) {
  48126. if (this.panningDistanceLimit) {
  48127. this._transformedDirection.addInPlace(this._target);
  48128. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48129. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48130. this._target.copyFrom(this._transformedDirection);
  48131. }
  48132. }
  48133. else {
  48134. this._target.addInPlace(this._transformedDirection);
  48135. }
  48136. }
  48137. this.inertialPanningX *= this.panningInertia;
  48138. this.inertialPanningY *= this.panningInertia;
  48139. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48140. this.inertialPanningX = 0;
  48141. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48142. this.inertialPanningY = 0;
  48143. }
  48144. // Limits
  48145. this._checkLimits();
  48146. _super.prototype._checkInputs.call(this);
  48147. };
  48148. ArcRotateCamera.prototype._checkLimits = function () {
  48149. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48150. if (this.allowUpsideDown && this.beta > Math.PI) {
  48151. this.beta = this.beta - (2 * Math.PI);
  48152. }
  48153. }
  48154. else {
  48155. if (this.beta < this.lowerBetaLimit) {
  48156. this.beta = this.lowerBetaLimit;
  48157. }
  48158. }
  48159. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48160. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48161. this.beta = this.beta + (2 * Math.PI);
  48162. }
  48163. }
  48164. else {
  48165. if (this.beta > this.upperBetaLimit) {
  48166. this.beta = this.upperBetaLimit;
  48167. }
  48168. }
  48169. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48170. this.alpha = this.lowerAlphaLimit;
  48171. }
  48172. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48173. this.alpha = this.upperAlphaLimit;
  48174. }
  48175. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48176. this.radius = this.lowerRadiusLimit;
  48177. }
  48178. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48179. this.radius = this.upperRadiusLimit;
  48180. }
  48181. };
  48182. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48183. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48184. this.radius = this._computationVector.length();
  48185. if (this.radius === 0) {
  48186. this.radius = 0.0001; // Just to avoid division by zero
  48187. }
  48188. // Alpha
  48189. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48190. if (this._computationVector.z < 0) {
  48191. this.alpha = 2 * Math.PI - this.alpha;
  48192. }
  48193. // Beta
  48194. this.beta = Math.acos(this._computationVector.y / this.radius);
  48195. this._checkLimits();
  48196. };
  48197. ArcRotateCamera.prototype.setPosition = function (position) {
  48198. if (this.position.equals(position)) {
  48199. return;
  48200. }
  48201. this.position.copyFrom(position);
  48202. this.rebuildAnglesAndRadius();
  48203. };
  48204. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48205. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48206. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48207. if (target.getBoundingInfo) {
  48208. if (toBoundingCenter) {
  48209. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48210. }
  48211. else {
  48212. this._targetBoundingCenter = null;
  48213. }
  48214. this._targetHost = target;
  48215. this._target = this._getTargetPosition();
  48216. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48217. }
  48218. else {
  48219. var newTarget = target;
  48220. var currentTarget = this._getTargetPosition();
  48221. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48222. return;
  48223. }
  48224. this._targetHost = null;
  48225. this._target = newTarget;
  48226. this._targetBoundingCenter = null;
  48227. this.onMeshTargetChangedObservable.notifyObservers(null);
  48228. }
  48229. this.rebuildAnglesAndRadius();
  48230. };
  48231. /** @hidden */
  48232. ArcRotateCamera.prototype._getViewMatrix = function () {
  48233. // Compute
  48234. var cosa = Math.cos(this.alpha);
  48235. var sina = Math.sin(this.alpha);
  48236. var cosb = Math.cos(this.beta);
  48237. var sinb = Math.sin(this.beta);
  48238. if (sinb === 0) {
  48239. sinb = 0.0001;
  48240. }
  48241. var target = this._getTargetPosition();
  48242. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48243. target.addToRef(this._computationVector, this._newPosition);
  48244. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48245. if (!this._collider) {
  48246. this._collider = new BABYLON.Collider();
  48247. }
  48248. this._collider._radius = this.collisionRadius;
  48249. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48250. this._collisionTriggered = true;
  48251. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48252. }
  48253. else {
  48254. this.position.copyFrom(this._newPosition);
  48255. var up = this.upVector;
  48256. if (this.allowUpsideDown && sinb < 0) {
  48257. up = up.clone();
  48258. up = up.negate();
  48259. }
  48260. this._computeViewMatrix(this.position, target, up);
  48261. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48262. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48263. }
  48264. this._currentTarget = target;
  48265. return this._viewMatrix;
  48266. };
  48267. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48268. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48269. meshes = meshes || this.getScene().meshes;
  48270. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48271. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48272. this.radius = distance * this.zoomOnFactor;
  48273. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48274. };
  48275. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48276. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48277. var meshesOrMinMaxVector;
  48278. var distance;
  48279. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48280. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48281. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48282. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48283. }
  48284. else { //minMaxVector and distance
  48285. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48286. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48287. distance = minMaxVectorAndDistance.distance;
  48288. }
  48289. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48290. if (!doNotUpdateMaxZ) {
  48291. this.maxZ = distance * 2;
  48292. }
  48293. };
  48294. /**
  48295. * @override
  48296. * Override Camera.createRigCamera
  48297. */
  48298. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48299. var alphaShift = 0;
  48300. switch (this.cameraRigMode) {
  48301. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48302. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48303. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48304. case BABYLON.Camera.RIG_MODE_VR:
  48305. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48306. break;
  48307. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48308. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48309. break;
  48310. }
  48311. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48312. rigCam._cameraRigParams = {};
  48313. return rigCam;
  48314. };
  48315. /**
  48316. * @hidden
  48317. * @override
  48318. * Override Camera._updateRigCameras
  48319. */
  48320. ArcRotateCamera.prototype._updateRigCameras = function () {
  48321. var camLeft = this._rigCameras[0];
  48322. var camRight = this._rigCameras[1];
  48323. camLeft.beta = camRight.beta = this.beta;
  48324. camLeft.radius = camRight.radius = this.radius;
  48325. switch (this.cameraRigMode) {
  48326. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48327. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48328. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48329. case BABYLON.Camera.RIG_MODE_VR:
  48330. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48331. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48332. break;
  48333. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48334. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48335. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48336. break;
  48337. }
  48338. _super.prototype._updateRigCameras.call(this);
  48339. };
  48340. ArcRotateCamera.prototype.dispose = function () {
  48341. this.inputs.clear();
  48342. _super.prototype.dispose.call(this);
  48343. };
  48344. ArcRotateCamera.prototype.getClassName = function () {
  48345. return "ArcRotateCamera";
  48346. };
  48347. __decorate([
  48348. BABYLON.serialize()
  48349. ], ArcRotateCamera.prototype, "alpha", void 0);
  48350. __decorate([
  48351. BABYLON.serialize()
  48352. ], ArcRotateCamera.prototype, "beta", void 0);
  48353. __decorate([
  48354. BABYLON.serialize()
  48355. ], ArcRotateCamera.prototype, "radius", void 0);
  48356. __decorate([
  48357. BABYLON.serializeAsVector3("target")
  48358. ], ArcRotateCamera.prototype, "_target", void 0);
  48359. __decorate([
  48360. BABYLON.serialize()
  48361. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48362. __decorate([
  48363. BABYLON.serialize()
  48364. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48365. __decorate([
  48366. BABYLON.serialize()
  48367. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48368. __decorate([
  48369. BABYLON.serialize()
  48370. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48371. __decorate([
  48372. BABYLON.serialize()
  48373. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48374. __decorate([
  48375. BABYLON.serialize()
  48376. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48377. __decorate([
  48378. BABYLON.serialize()
  48379. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48380. __decorate([
  48381. BABYLON.serialize()
  48382. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48383. __decorate([
  48384. BABYLON.serialize()
  48385. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48386. __decorate([
  48387. BABYLON.serialize()
  48388. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48389. __decorate([
  48390. BABYLON.serialize()
  48391. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48392. __decorate([
  48393. BABYLON.serialize()
  48394. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48395. __decorate([
  48396. BABYLON.serialize()
  48397. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48398. __decorate([
  48399. BABYLON.serializeAsVector3()
  48400. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48401. __decorate([
  48402. BABYLON.serialize()
  48403. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48404. __decorate([
  48405. BABYLON.serialize()
  48406. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48407. __decorate([
  48408. BABYLON.serialize()
  48409. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48410. return ArcRotateCamera;
  48411. }(BABYLON.TargetCamera));
  48412. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48413. })(BABYLON || (BABYLON = {}));
  48414. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48415. var BABYLON;
  48416. (function (BABYLON) {
  48417. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48418. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48419. });
  48420. /**
  48421. * The HemisphericLight simulates the ambient environment light,
  48422. * so the passed direction is the light reflection direction, not the incoming direction.
  48423. */
  48424. var HemisphericLight = /** @class */ (function (_super) {
  48425. __extends(HemisphericLight, _super);
  48426. /**
  48427. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48428. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48429. * The HemisphericLight can't cast shadows.
  48430. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48431. * @param name The friendly name of the light
  48432. * @param direction The direction of the light reflection
  48433. * @param scene The scene the light belongs to
  48434. */
  48435. function HemisphericLight(name, direction, scene) {
  48436. var _this = _super.call(this, name, scene) || this;
  48437. /**
  48438. * The groundColor is the light in the opposite direction to the one specified during creation.
  48439. * 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.
  48440. */
  48441. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48442. _this.direction = direction || BABYLON.Vector3.Up();
  48443. return _this;
  48444. }
  48445. HemisphericLight.prototype._buildUniformLayout = function () {
  48446. this._uniformBuffer.addUniform("vLightData", 4);
  48447. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48448. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48449. this._uniformBuffer.addUniform("vLightGround", 3);
  48450. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48451. this._uniformBuffer.addUniform("depthValues", 2);
  48452. this._uniformBuffer.create();
  48453. };
  48454. /**
  48455. * Returns the string "HemisphericLight".
  48456. * @return The class name
  48457. */
  48458. HemisphericLight.prototype.getClassName = function () {
  48459. return "HemisphericLight";
  48460. };
  48461. /**
  48462. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48463. * Returns the updated direction.
  48464. * @param target The target the direction should point to
  48465. * @return The computed direction
  48466. */
  48467. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48468. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48469. return this.direction;
  48470. };
  48471. /**
  48472. * Returns the shadow generator associated to the light.
  48473. * @returns Always null for hemispheric lights because it does not support shadows.
  48474. */
  48475. HemisphericLight.prototype.getShadowGenerator = function () {
  48476. return null;
  48477. };
  48478. /**
  48479. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48480. * @param effect The effect to update
  48481. * @param lightIndex The index of the light in the effect to update
  48482. * @returns The hemispheric light
  48483. */
  48484. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48485. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48486. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48487. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48488. return this;
  48489. };
  48490. /**
  48491. * @hidden internal use only.
  48492. */
  48493. HemisphericLight.prototype._getWorldMatrix = function () {
  48494. if (!this._worldMatrix) {
  48495. this._worldMatrix = BABYLON.Matrix.Identity();
  48496. }
  48497. return this._worldMatrix;
  48498. };
  48499. /**
  48500. * Returns the integer 3.
  48501. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48502. */
  48503. HemisphericLight.prototype.getTypeID = function () {
  48504. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48505. };
  48506. /**
  48507. * Prepares the list of defines specific to the light type.
  48508. * @param defines the list of defines
  48509. * @param lightIndex defines the index of the light for the effect
  48510. */
  48511. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48512. defines["HEMILIGHT" + lightIndex] = true;
  48513. };
  48514. __decorate([
  48515. BABYLON.serializeAsColor3()
  48516. ], HemisphericLight.prototype, "groundColor", void 0);
  48517. __decorate([
  48518. BABYLON.serializeAsVector3()
  48519. ], HemisphericLight.prototype, "direction", void 0);
  48520. return HemisphericLight;
  48521. }(BABYLON.Light));
  48522. BABYLON.HemisphericLight = HemisphericLight;
  48523. })(BABYLON || (BABYLON = {}));
  48524. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48525. var BABYLON;
  48526. (function (BABYLON) {
  48527. /**
  48528. * Base implementation IShadowLight
  48529. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48530. */
  48531. var ShadowLight = /** @class */ (function (_super) {
  48532. __extends(ShadowLight, _super);
  48533. function ShadowLight() {
  48534. var _this = _super !== null && _super.apply(this, arguments) || this;
  48535. _this._needProjectionMatrixCompute = true;
  48536. return _this;
  48537. }
  48538. ShadowLight.prototype._setPosition = function (value) {
  48539. this._position = value;
  48540. };
  48541. Object.defineProperty(ShadowLight.prototype, "position", {
  48542. /**
  48543. * Sets the position the shadow will be casted from. Also use as the light position for both
  48544. * point and spot lights.
  48545. */
  48546. get: function () {
  48547. return this._position;
  48548. },
  48549. /**
  48550. * Sets the position the shadow will be casted from. Also use as the light position for both
  48551. * point and spot lights.
  48552. */
  48553. set: function (value) {
  48554. this._setPosition(value);
  48555. },
  48556. enumerable: true,
  48557. configurable: true
  48558. });
  48559. ShadowLight.prototype._setDirection = function (value) {
  48560. this._direction = value;
  48561. };
  48562. Object.defineProperty(ShadowLight.prototype, "direction", {
  48563. /**
  48564. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48565. * Also use as the light direction on spot and directional lights.
  48566. */
  48567. get: function () {
  48568. return this._direction;
  48569. },
  48570. /**
  48571. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48572. * Also use as the light direction on spot and directional lights.
  48573. */
  48574. set: function (value) {
  48575. this._setDirection(value);
  48576. },
  48577. enumerable: true,
  48578. configurable: true
  48579. });
  48580. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48581. /**
  48582. * Gets the shadow projection clipping minimum z value.
  48583. */
  48584. get: function () {
  48585. return this._shadowMinZ;
  48586. },
  48587. /**
  48588. * Sets the shadow projection clipping minimum z value.
  48589. */
  48590. set: function (value) {
  48591. this._shadowMinZ = value;
  48592. this.forceProjectionMatrixCompute();
  48593. },
  48594. enumerable: true,
  48595. configurable: true
  48596. });
  48597. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48598. /**
  48599. * Sets the shadow projection clipping maximum z value.
  48600. */
  48601. get: function () {
  48602. return this._shadowMaxZ;
  48603. },
  48604. /**
  48605. * Gets the shadow projection clipping maximum z value.
  48606. */
  48607. set: function (value) {
  48608. this._shadowMaxZ = value;
  48609. this.forceProjectionMatrixCompute();
  48610. },
  48611. enumerable: true,
  48612. configurable: true
  48613. });
  48614. /**
  48615. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48616. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48617. */
  48618. ShadowLight.prototype.computeTransformedInformation = function () {
  48619. if (this.parent && this.parent.getWorldMatrix) {
  48620. if (!this.transformedPosition) {
  48621. this.transformedPosition = BABYLON.Vector3.Zero();
  48622. }
  48623. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48624. // In case the direction is present.
  48625. if (this.direction) {
  48626. if (!this.transformedDirection) {
  48627. this.transformedDirection = BABYLON.Vector3.Zero();
  48628. }
  48629. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48630. }
  48631. return true;
  48632. }
  48633. return false;
  48634. };
  48635. /**
  48636. * Return the depth scale used for the shadow map.
  48637. * @returns the depth scale.
  48638. */
  48639. ShadowLight.prototype.getDepthScale = function () {
  48640. return 50.0;
  48641. };
  48642. /**
  48643. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48644. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48645. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48646. */
  48647. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48648. return this.transformedDirection ? this.transformedDirection : this.direction;
  48649. };
  48650. /**
  48651. * Returns the ShadowLight absolute position in the World.
  48652. * @returns the position vector in world space
  48653. */
  48654. ShadowLight.prototype.getAbsolutePosition = function () {
  48655. return this.transformedPosition ? this.transformedPosition : this.position;
  48656. };
  48657. /**
  48658. * Sets the ShadowLight direction toward the passed target.
  48659. * @param target The point tot target in local space
  48660. * @returns the updated ShadowLight direction
  48661. */
  48662. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48663. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48664. return this.direction;
  48665. };
  48666. /**
  48667. * Returns the light rotation in euler definition.
  48668. * @returns the x y z rotation in local space.
  48669. */
  48670. ShadowLight.prototype.getRotation = function () {
  48671. this.direction.normalize();
  48672. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48673. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48674. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48675. };
  48676. /**
  48677. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48678. * @returns true if a cube texture needs to be use
  48679. */
  48680. ShadowLight.prototype.needCube = function () {
  48681. return false;
  48682. };
  48683. /**
  48684. * Detects if the projection matrix requires to be recomputed this frame.
  48685. * @returns true if it requires to be recomputed otherwise, false.
  48686. */
  48687. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48688. return this._needProjectionMatrixCompute;
  48689. };
  48690. /**
  48691. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48692. */
  48693. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48694. this._needProjectionMatrixCompute = true;
  48695. };
  48696. /**
  48697. * Get the world matrix of the sahdow lights.
  48698. * @hidden Internal Use Only
  48699. */
  48700. ShadowLight.prototype._getWorldMatrix = function () {
  48701. if (!this._worldMatrix) {
  48702. this._worldMatrix = BABYLON.Matrix.Identity();
  48703. }
  48704. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48705. return this._worldMatrix;
  48706. };
  48707. /**
  48708. * Gets the minZ used for shadow according to both the scene and the light.
  48709. * @param activeCamera The camera we are returning the min for
  48710. * @returns the depth min z
  48711. */
  48712. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48713. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48714. };
  48715. /**
  48716. * Gets the maxZ used for shadow according to both the scene and the light.
  48717. * @param activeCamera The camera we are returning the max for
  48718. * @returns the depth max z
  48719. */
  48720. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48721. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48722. };
  48723. /**
  48724. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48725. * @param matrix The materix to updated with the projection information
  48726. * @param viewMatrix The transform matrix of the light
  48727. * @param renderList The list of mesh to render in the map
  48728. * @returns The current light
  48729. */
  48730. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48731. if (this.customProjectionMatrixBuilder) {
  48732. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48733. }
  48734. else {
  48735. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48736. }
  48737. return this;
  48738. };
  48739. __decorate([
  48740. BABYLON.serializeAsVector3()
  48741. ], ShadowLight.prototype, "position", null);
  48742. __decorate([
  48743. BABYLON.serializeAsVector3()
  48744. ], ShadowLight.prototype, "direction", null);
  48745. __decorate([
  48746. BABYLON.serialize()
  48747. ], ShadowLight.prototype, "shadowMinZ", null);
  48748. __decorate([
  48749. BABYLON.serialize()
  48750. ], ShadowLight.prototype, "shadowMaxZ", null);
  48751. return ShadowLight;
  48752. }(BABYLON.Light));
  48753. BABYLON.ShadowLight = ShadowLight;
  48754. })(BABYLON || (BABYLON = {}));
  48755. //# sourceMappingURL=babylon.shadowLight.js.map
  48756. var BABYLON;
  48757. (function (BABYLON) {
  48758. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48759. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48760. });
  48761. /**
  48762. * A point light is a light defined by an unique point in world space.
  48763. * The light is emitted in every direction from this point.
  48764. * A good example of a point light is a standard light bulb.
  48765. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48766. */
  48767. var PointLight = /** @class */ (function (_super) {
  48768. __extends(PointLight, _super);
  48769. /**
  48770. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48771. * A PointLight emits the light in every direction.
  48772. * It can cast shadows.
  48773. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48774. * ```javascript
  48775. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48776. * ```
  48777. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48778. * @param name The light friendly name
  48779. * @param position The position of the point light in the scene
  48780. * @param scene The scene the lights belongs to
  48781. */
  48782. function PointLight(name, position, scene) {
  48783. var _this = _super.call(this, name, scene) || this;
  48784. _this._shadowAngle = Math.PI / 2;
  48785. _this.position = position;
  48786. return _this;
  48787. }
  48788. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48789. /**
  48790. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48791. * This specifies what angle the shadow will use to be created.
  48792. *
  48793. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48794. */
  48795. get: function () {
  48796. return this._shadowAngle;
  48797. },
  48798. /**
  48799. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48800. * This specifies what angle the shadow will use to be created.
  48801. *
  48802. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48803. */
  48804. set: function (value) {
  48805. this._shadowAngle = value;
  48806. this.forceProjectionMatrixCompute();
  48807. },
  48808. enumerable: true,
  48809. configurable: true
  48810. });
  48811. Object.defineProperty(PointLight.prototype, "direction", {
  48812. /**
  48813. * Gets the direction if it has been set.
  48814. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48815. */
  48816. get: function () {
  48817. return this._direction;
  48818. },
  48819. /**
  48820. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48821. */
  48822. set: function (value) {
  48823. var previousNeedCube = this.needCube();
  48824. this._direction = value;
  48825. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48826. this._shadowGenerator.recreateShadowMap();
  48827. }
  48828. },
  48829. enumerable: true,
  48830. configurable: true
  48831. });
  48832. /**
  48833. * Returns the string "PointLight"
  48834. * @returns the class name
  48835. */
  48836. PointLight.prototype.getClassName = function () {
  48837. return "PointLight";
  48838. };
  48839. /**
  48840. * Returns the integer 0.
  48841. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48842. */
  48843. PointLight.prototype.getTypeID = function () {
  48844. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48845. };
  48846. /**
  48847. * Specifies wether or not the shadowmap should be a cube texture.
  48848. * @returns true if the shadowmap needs to be a cube texture.
  48849. */
  48850. PointLight.prototype.needCube = function () {
  48851. return !this.direction;
  48852. };
  48853. /**
  48854. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48855. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48856. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48857. */
  48858. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48859. if (this.direction) {
  48860. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48861. }
  48862. else {
  48863. switch (faceIndex) {
  48864. case 0:
  48865. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48866. case 1:
  48867. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48868. case 2:
  48869. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48870. case 3:
  48871. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48872. case 4:
  48873. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48874. case 5:
  48875. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48876. }
  48877. }
  48878. return BABYLON.Vector3.Zero();
  48879. };
  48880. /**
  48881. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48882. * - fov = PI / 2
  48883. * - aspect ratio : 1.0
  48884. * - z-near and far equal to the active camera minZ and maxZ.
  48885. * Returns the PointLight.
  48886. */
  48887. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48888. var activeCamera = this.getScene().activeCamera;
  48889. if (!activeCamera) {
  48890. return;
  48891. }
  48892. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48893. };
  48894. PointLight.prototype._buildUniformLayout = function () {
  48895. this._uniformBuffer.addUniform("vLightData", 4);
  48896. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48897. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48898. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48899. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48900. this._uniformBuffer.addUniform("depthValues", 2);
  48901. this._uniformBuffer.create();
  48902. };
  48903. /**
  48904. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48905. * @param effect The effect to update
  48906. * @param lightIndex The index of the light in the effect to update
  48907. * @returns The point light
  48908. */
  48909. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48910. if (this.computeTransformedInformation()) {
  48911. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48912. }
  48913. else {
  48914. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48915. }
  48916. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48917. return this;
  48918. };
  48919. /**
  48920. * Prepares the list of defines specific to the light type.
  48921. * @param defines the list of defines
  48922. * @param lightIndex defines the index of the light for the effect
  48923. */
  48924. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48925. defines["POINTLIGHT" + lightIndex] = true;
  48926. };
  48927. __decorate([
  48928. BABYLON.serialize()
  48929. ], PointLight.prototype, "shadowAngle", null);
  48930. return PointLight;
  48931. }(BABYLON.ShadowLight));
  48932. BABYLON.PointLight = PointLight;
  48933. })(BABYLON || (BABYLON = {}));
  48934. //# sourceMappingURL=babylon.pointLight.js.map
  48935. var BABYLON;
  48936. (function (BABYLON) {
  48937. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48938. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48939. });
  48940. /**
  48941. * A directional light is defined by a direction (what a surprise!).
  48942. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48943. * 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.
  48944. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48945. */
  48946. var DirectionalLight = /** @class */ (function (_super) {
  48947. __extends(DirectionalLight, _super);
  48948. /**
  48949. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48950. * The directional light is emitted from everywhere in the given direction.
  48951. * It can cast shawdows.
  48952. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48953. * @param name The friendly name of the light
  48954. * @param direction The direction of the light
  48955. * @param scene The scene the light belongs to
  48956. */
  48957. function DirectionalLight(name, direction, scene) {
  48958. var _this = _super.call(this, name, scene) || this;
  48959. _this._shadowFrustumSize = 0;
  48960. _this._shadowOrthoScale = 0.1;
  48961. /**
  48962. * Automatically compute the projection matrix to best fit (including all the casters)
  48963. * on each frame.
  48964. */
  48965. _this.autoUpdateExtends = true;
  48966. // Cache
  48967. _this._orthoLeft = Number.MAX_VALUE;
  48968. _this._orthoRight = Number.MIN_VALUE;
  48969. _this._orthoTop = Number.MIN_VALUE;
  48970. _this._orthoBottom = Number.MAX_VALUE;
  48971. _this.position = direction.scale(-1.0);
  48972. _this.direction = direction;
  48973. return _this;
  48974. }
  48975. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48976. /**
  48977. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48978. */
  48979. get: function () {
  48980. return this._shadowFrustumSize;
  48981. },
  48982. /**
  48983. * Specifies a fix frustum size for the shadow generation.
  48984. */
  48985. set: function (value) {
  48986. this._shadowFrustumSize = value;
  48987. this.forceProjectionMatrixCompute();
  48988. },
  48989. enumerable: true,
  48990. configurable: true
  48991. });
  48992. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48993. /**
  48994. * Gets the shadow projection scale against the optimal computed one.
  48995. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48996. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48997. */
  48998. get: function () {
  48999. return this._shadowOrthoScale;
  49000. },
  49001. /**
  49002. * Sets the shadow projection scale against the optimal computed one.
  49003. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49004. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49005. */
  49006. set: function (value) {
  49007. this._shadowOrthoScale = value;
  49008. this.forceProjectionMatrixCompute();
  49009. },
  49010. enumerable: true,
  49011. configurable: true
  49012. });
  49013. /**
  49014. * Returns the string "DirectionalLight".
  49015. * @return The class name
  49016. */
  49017. DirectionalLight.prototype.getClassName = function () {
  49018. return "DirectionalLight";
  49019. };
  49020. /**
  49021. * Returns the integer 1.
  49022. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49023. */
  49024. DirectionalLight.prototype.getTypeID = function () {
  49025. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49026. };
  49027. /**
  49028. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49029. * Returns the DirectionalLight Shadow projection matrix.
  49030. */
  49031. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49032. if (this.shadowFrustumSize > 0) {
  49033. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49034. }
  49035. else {
  49036. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49037. }
  49038. };
  49039. /**
  49040. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49041. * Returns the DirectionalLight Shadow projection matrix.
  49042. */
  49043. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49044. var activeCamera = this.getScene().activeCamera;
  49045. if (!activeCamera) {
  49046. return;
  49047. }
  49048. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49049. };
  49050. /**
  49051. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49052. * Returns the DirectionalLight Shadow projection matrix.
  49053. */
  49054. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49055. var activeCamera = this.getScene().activeCamera;
  49056. if (!activeCamera) {
  49057. return;
  49058. }
  49059. // Check extends
  49060. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49061. var tempVector3 = BABYLON.Vector3.Zero();
  49062. this._orthoLeft = Number.MAX_VALUE;
  49063. this._orthoRight = Number.MIN_VALUE;
  49064. this._orthoTop = Number.MIN_VALUE;
  49065. this._orthoBottom = Number.MAX_VALUE;
  49066. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49067. var mesh = renderList[meshIndex];
  49068. if (!mesh) {
  49069. continue;
  49070. }
  49071. var boundingInfo = mesh.getBoundingInfo();
  49072. var boundingBox = boundingInfo.boundingBox;
  49073. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49074. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49075. if (tempVector3.x < this._orthoLeft)
  49076. this._orthoLeft = tempVector3.x;
  49077. if (tempVector3.y < this._orthoBottom)
  49078. this._orthoBottom = tempVector3.y;
  49079. if (tempVector3.x > this._orthoRight)
  49080. this._orthoRight = tempVector3.x;
  49081. if (tempVector3.y > this._orthoTop)
  49082. this._orthoTop = tempVector3.y;
  49083. }
  49084. }
  49085. }
  49086. var xOffset = this._orthoRight - this._orthoLeft;
  49087. var yOffset = this._orthoTop - this._orthoBottom;
  49088. 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);
  49089. };
  49090. DirectionalLight.prototype._buildUniformLayout = function () {
  49091. this._uniformBuffer.addUniform("vLightData", 4);
  49092. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49093. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49094. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49095. this._uniformBuffer.addUniform("depthValues", 2);
  49096. this._uniformBuffer.create();
  49097. };
  49098. /**
  49099. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49100. * @param effect The effect to update
  49101. * @param lightIndex The index of the light in the effect to update
  49102. * @returns The directional light
  49103. */
  49104. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49105. if (this.computeTransformedInformation()) {
  49106. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49107. return this;
  49108. }
  49109. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49110. return this;
  49111. };
  49112. /**
  49113. * Gets the minZ used for shadow according to both the scene and the light.
  49114. *
  49115. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49116. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49117. * @param activeCamera The camera we are returning the min for
  49118. * @returns the depth min z
  49119. */
  49120. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49121. return 1;
  49122. };
  49123. /**
  49124. * Gets the maxZ used for shadow according to both the scene and the light.
  49125. *
  49126. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49127. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49128. * @param activeCamera The camera we are returning the max for
  49129. * @returns the depth max z
  49130. */
  49131. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49132. return 1;
  49133. };
  49134. /**
  49135. * Prepares the list of defines specific to the light type.
  49136. * @param defines the list of defines
  49137. * @param lightIndex defines the index of the light for the effect
  49138. */
  49139. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49140. defines["DIRLIGHT" + lightIndex] = true;
  49141. };
  49142. __decorate([
  49143. BABYLON.serialize()
  49144. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49145. __decorate([
  49146. BABYLON.serialize()
  49147. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49148. __decorate([
  49149. BABYLON.serialize()
  49150. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49151. return DirectionalLight;
  49152. }(BABYLON.ShadowLight));
  49153. BABYLON.DirectionalLight = DirectionalLight;
  49154. })(BABYLON || (BABYLON = {}));
  49155. //# sourceMappingURL=babylon.directionalLight.js.map
  49156. var BABYLON;
  49157. (function (BABYLON) {
  49158. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49159. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49160. });
  49161. /**
  49162. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49163. * These values define a cone of light starting from the position, emitting toward the direction.
  49164. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49165. * and the exponent defines the speed of the decay of the light with distance (reach).
  49166. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49167. */
  49168. var SpotLight = /** @class */ (function (_super) {
  49169. __extends(SpotLight, _super);
  49170. /**
  49171. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49172. * It can cast shadows.
  49173. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49174. * @param name The light friendly name
  49175. * @param position The position of the spot light in the scene
  49176. * @param direction The direction of the light in the scene
  49177. * @param angle The cone angle of the light in Radians
  49178. * @param exponent The light decay speed with the distance from the emission spot
  49179. * @param scene The scene the lights belongs to
  49180. */
  49181. function SpotLight(name, position, direction, angle, exponent, scene) {
  49182. var _this = _super.call(this, name, scene) || this;
  49183. _this._innerAngle = 0;
  49184. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49185. _this._projectionTextureLightNear = 1e-6;
  49186. _this._projectionTextureLightFar = 1000.0;
  49187. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49188. _this._projectionTextureViewLightDirty = true;
  49189. _this._projectionTextureProjectionLightDirty = true;
  49190. _this._projectionTextureDirty = true;
  49191. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49192. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49193. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49194. _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);
  49195. _this.position = position;
  49196. _this.direction = direction;
  49197. _this.angle = angle;
  49198. _this.exponent = exponent;
  49199. return _this;
  49200. }
  49201. Object.defineProperty(SpotLight.prototype, "angle", {
  49202. /**
  49203. * Gets the cone angle of the spot light in Radians.
  49204. */
  49205. get: function () {
  49206. return this._angle;
  49207. },
  49208. /**
  49209. * Sets the cone angle of the spot light in Radians.
  49210. */
  49211. set: function (value) {
  49212. this._angle = value;
  49213. this._cosHalfAngle = Math.cos(value * 0.5);
  49214. this._projectionTextureProjectionLightDirty = true;
  49215. this.forceProjectionMatrixCompute();
  49216. this._computeAngleValues();
  49217. },
  49218. enumerable: true,
  49219. configurable: true
  49220. });
  49221. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49222. /**
  49223. * Only used in gltf falloff mode, this defines the angle where
  49224. * the directional falloff will start before cutting at angle which could be seen
  49225. * as outer angle.
  49226. */
  49227. get: function () {
  49228. return this._angle;
  49229. },
  49230. /**
  49231. * Only used in gltf falloff mode, this defines the angle where
  49232. * the directional falloff will start before cutting at angle which could be seen
  49233. * as outer angle.
  49234. */
  49235. set: function (value) {
  49236. this._innerAngle = value;
  49237. this._computeAngleValues();
  49238. },
  49239. enumerable: true,
  49240. configurable: true
  49241. });
  49242. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49243. /**
  49244. * Allows scaling the angle of the light for shadow generation only.
  49245. */
  49246. get: function () {
  49247. return this._shadowAngleScale;
  49248. },
  49249. /**
  49250. * Allows scaling the angle of the light for shadow generation only.
  49251. */
  49252. set: function (value) {
  49253. this._shadowAngleScale = value;
  49254. this.forceProjectionMatrixCompute();
  49255. },
  49256. enumerable: true,
  49257. configurable: true
  49258. });
  49259. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49260. /**
  49261. * Allows reading the projecton texture
  49262. */
  49263. get: function () {
  49264. return this._projectionTextureMatrix;
  49265. },
  49266. enumerable: true,
  49267. configurable: true
  49268. });
  49269. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49270. /**
  49271. * Gets the near clip of the Spotlight for texture projection.
  49272. */
  49273. get: function () {
  49274. return this._projectionTextureLightNear;
  49275. },
  49276. /**
  49277. * Sets the near clip of the Spotlight for texture projection.
  49278. */
  49279. set: function (value) {
  49280. this._projectionTextureLightNear = value;
  49281. this._projectionTextureProjectionLightDirty = true;
  49282. },
  49283. enumerable: true,
  49284. configurable: true
  49285. });
  49286. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49287. /**
  49288. * Gets the far clip of the Spotlight for texture projection.
  49289. */
  49290. get: function () {
  49291. return this._projectionTextureLightFar;
  49292. },
  49293. /**
  49294. * Sets the far clip of the Spotlight for texture projection.
  49295. */
  49296. set: function (value) {
  49297. this._projectionTextureLightFar = value;
  49298. this._projectionTextureProjectionLightDirty = true;
  49299. },
  49300. enumerable: true,
  49301. configurable: true
  49302. });
  49303. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49304. /**
  49305. * Gets the Up vector of the Spotlight for texture projection.
  49306. */
  49307. get: function () {
  49308. return this._projectionTextureUpDirection;
  49309. },
  49310. /**
  49311. * Sets the Up vector of the Spotlight for texture projection.
  49312. */
  49313. set: function (value) {
  49314. this._projectionTextureUpDirection = value;
  49315. this._projectionTextureProjectionLightDirty = true;
  49316. },
  49317. enumerable: true,
  49318. configurable: true
  49319. });
  49320. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49321. /**
  49322. * Gets the projection texture of the light.
  49323. */
  49324. get: function () {
  49325. return this._projectionTexture;
  49326. },
  49327. /**
  49328. * Sets the projection texture of the light.
  49329. */
  49330. set: function (value) {
  49331. this._projectionTexture = value;
  49332. this._projectionTextureDirty = true;
  49333. },
  49334. enumerable: true,
  49335. configurable: true
  49336. });
  49337. /**
  49338. * Returns the string "SpotLight".
  49339. * @returns the class name
  49340. */
  49341. SpotLight.prototype.getClassName = function () {
  49342. return "SpotLight";
  49343. };
  49344. /**
  49345. * Returns the integer 2.
  49346. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49347. */
  49348. SpotLight.prototype.getTypeID = function () {
  49349. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49350. };
  49351. /**
  49352. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49353. */
  49354. SpotLight.prototype._setDirection = function (value) {
  49355. _super.prototype._setDirection.call(this, value);
  49356. this._projectionTextureViewLightDirty = true;
  49357. };
  49358. /**
  49359. * Overrides the position setter to recompute the projection texture view light Matrix.
  49360. */
  49361. SpotLight.prototype._setPosition = function (value) {
  49362. _super.prototype._setPosition.call(this, value);
  49363. this._projectionTextureViewLightDirty = true;
  49364. };
  49365. /**
  49366. * 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.
  49367. * Returns the SpotLight.
  49368. */
  49369. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49370. var activeCamera = this.getScene().activeCamera;
  49371. if (!activeCamera) {
  49372. return;
  49373. }
  49374. this._shadowAngleScale = this._shadowAngleScale || 1;
  49375. var angle = this._shadowAngleScale * this._angle;
  49376. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49377. };
  49378. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49379. this._projectionTextureViewLightDirty = false;
  49380. this._projectionTextureDirty = true;
  49381. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49382. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49383. };
  49384. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49385. this._projectionTextureProjectionLightDirty = false;
  49386. this._projectionTextureDirty = true;
  49387. var light_far = this.projectionTextureLightFar;
  49388. var light_near = this.projectionTextureLightNear;
  49389. var P = light_far / (light_far - light_near);
  49390. var Q = -P * light_near;
  49391. var S = 1.0 / Math.tan(this._angle / 2.0);
  49392. var A = 1.0;
  49393. 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);
  49394. };
  49395. /**
  49396. * Main function for light texture projection matrix computing.
  49397. */
  49398. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49399. this._projectionTextureDirty = false;
  49400. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49401. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49402. };
  49403. SpotLight.prototype._buildUniformLayout = function () {
  49404. this._uniformBuffer.addUniform("vLightData", 4);
  49405. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49406. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49407. this._uniformBuffer.addUniform("vLightDirection", 3);
  49408. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49409. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49410. this._uniformBuffer.addUniform("depthValues", 2);
  49411. this._uniformBuffer.create();
  49412. };
  49413. SpotLight.prototype._computeAngleValues = function () {
  49414. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49415. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49416. };
  49417. /**
  49418. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49419. * @param effect The effect to update
  49420. * @param lightIndex The index of the light in the effect to update
  49421. * @returns The spot light
  49422. */
  49423. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49424. var normalizeDirection;
  49425. if (this.computeTransformedInformation()) {
  49426. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49427. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49428. }
  49429. else {
  49430. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49431. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49432. }
  49433. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49434. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49435. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49436. if (this._projectionTextureViewLightDirty) {
  49437. this._computeProjectionTextureViewLightMatrix();
  49438. }
  49439. if (this._projectionTextureProjectionLightDirty) {
  49440. this._computeProjectionTextureProjectionLightMatrix();
  49441. }
  49442. if (this._projectionTextureDirty) {
  49443. this._computeProjectionTextureMatrix();
  49444. }
  49445. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49446. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49447. }
  49448. return this;
  49449. };
  49450. /**
  49451. * Disposes the light and the associated resources.
  49452. */
  49453. SpotLight.prototype.dispose = function () {
  49454. _super.prototype.dispose.call(this);
  49455. if (this._projectionTexture) {
  49456. this._projectionTexture.dispose();
  49457. }
  49458. };
  49459. /**
  49460. * Prepares the list of defines specific to the light type.
  49461. * @param defines the list of defines
  49462. * @param lightIndex defines the index of the light for the effect
  49463. */
  49464. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49465. defines["SPOTLIGHT" + lightIndex] = true;
  49466. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49467. };
  49468. __decorate([
  49469. BABYLON.serialize()
  49470. ], SpotLight.prototype, "angle", null);
  49471. __decorate([
  49472. BABYLON.serialize()
  49473. ], SpotLight.prototype, "innerAngle", null);
  49474. __decorate([
  49475. BABYLON.serialize()
  49476. ], SpotLight.prototype, "shadowAngleScale", null);
  49477. __decorate([
  49478. BABYLON.serialize()
  49479. ], SpotLight.prototype, "exponent", void 0);
  49480. __decorate([
  49481. BABYLON.serialize()
  49482. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49483. __decorate([
  49484. BABYLON.serialize()
  49485. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49486. __decorate([
  49487. BABYLON.serialize()
  49488. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49489. __decorate([
  49490. BABYLON.serializeAsTexture("projectedLightTexture")
  49491. ], SpotLight.prototype, "_projectionTexture", void 0);
  49492. return SpotLight;
  49493. }(BABYLON.ShadowLight));
  49494. BABYLON.SpotLight = SpotLight;
  49495. })(BABYLON || (BABYLON = {}));
  49496. //# sourceMappingURL=babylon.spotLight.js.map
  49497. var BABYLON;
  49498. (function (BABYLON) {
  49499. /**
  49500. * Class used to override all child animations of a given target
  49501. */
  49502. var AnimationPropertiesOverride = /** @class */ (function () {
  49503. function AnimationPropertiesOverride() {
  49504. /**
  49505. * Gets or sets a value indicating if animation blending must be used
  49506. */
  49507. this.enableBlending = false;
  49508. /**
  49509. * Gets or sets the blending speed to use when enableBlending is true
  49510. */
  49511. this.blendingSpeed = 0.01;
  49512. /**
  49513. * Gets or sets the default loop mode to use
  49514. */
  49515. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49516. }
  49517. return AnimationPropertiesOverride;
  49518. }());
  49519. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49520. })(BABYLON || (BABYLON = {}));
  49521. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49522. var BABYLON;
  49523. (function (BABYLON) {
  49524. /**
  49525. * Represents the range of an animation
  49526. */
  49527. var AnimationRange = /** @class */ (function () {
  49528. /**
  49529. * Initializes the range of an animation
  49530. * @param name The name of the animation range
  49531. * @param from The starting frame of the animation
  49532. * @param to The ending frame of the animation
  49533. */
  49534. function AnimationRange(
  49535. /**The name of the animation range**/
  49536. name,
  49537. /**The starting frame of the animation */
  49538. from,
  49539. /**The ending frame of the animation*/
  49540. to) {
  49541. this.name = name;
  49542. this.from = from;
  49543. this.to = to;
  49544. }
  49545. /**
  49546. * Makes a copy of the animation range
  49547. * @returns A copy of the animation range
  49548. */
  49549. AnimationRange.prototype.clone = function () {
  49550. return new AnimationRange(this.name, this.from, this.to);
  49551. };
  49552. return AnimationRange;
  49553. }());
  49554. BABYLON.AnimationRange = AnimationRange;
  49555. /**
  49556. * Composed of a frame, and an action function
  49557. */
  49558. var AnimationEvent = /** @class */ (function () {
  49559. /**
  49560. * Initializes the animation event
  49561. * @param frame The frame for which the event is triggered
  49562. * @param action The event to perform when triggered
  49563. * @param onlyOnce Specifies if the event should be triggered only once
  49564. */
  49565. function AnimationEvent(
  49566. /** The frame for which the event is triggered **/
  49567. frame,
  49568. /** The event to perform when triggered **/
  49569. action,
  49570. /** Specifies if the event should be triggered only once**/
  49571. onlyOnce) {
  49572. this.frame = frame;
  49573. this.action = action;
  49574. this.onlyOnce = onlyOnce;
  49575. /**
  49576. * Specifies if the animation event is done
  49577. */
  49578. this.isDone = false;
  49579. }
  49580. /** @hidden */
  49581. AnimationEvent.prototype._clone = function () {
  49582. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49583. };
  49584. return AnimationEvent;
  49585. }());
  49586. BABYLON.AnimationEvent = AnimationEvent;
  49587. /**
  49588. * A cursor which tracks a point on a path
  49589. */
  49590. var PathCursor = /** @class */ (function () {
  49591. /**
  49592. * Initializes the path cursor
  49593. * @param path The path to track
  49594. */
  49595. function PathCursor(path) {
  49596. this.path = path;
  49597. /**
  49598. * Stores path cursor callbacks for when an onchange event is triggered
  49599. */
  49600. this._onchange = new Array();
  49601. /**
  49602. * The value of the path cursor
  49603. */
  49604. this.value = 0;
  49605. /**
  49606. * The animation array of the path cursor
  49607. */
  49608. this.animations = new Array();
  49609. }
  49610. /**
  49611. * Gets the cursor point on the path
  49612. * @returns A point on the path cursor at the cursor location
  49613. */
  49614. PathCursor.prototype.getPoint = function () {
  49615. var point = this.path.getPointAtLengthPosition(this.value);
  49616. return new BABYLON.Vector3(point.x, 0, point.y);
  49617. };
  49618. /**
  49619. * Moves the cursor ahead by the step amount
  49620. * @param step The amount to move the cursor forward
  49621. * @returns This path cursor
  49622. */
  49623. PathCursor.prototype.moveAhead = function (step) {
  49624. if (step === void 0) { step = 0.002; }
  49625. this.move(step);
  49626. return this;
  49627. };
  49628. /**
  49629. * Moves the cursor behind by the step amount
  49630. * @param step The amount to move the cursor back
  49631. * @returns This path cursor
  49632. */
  49633. PathCursor.prototype.moveBack = function (step) {
  49634. if (step === void 0) { step = 0.002; }
  49635. this.move(-step);
  49636. return this;
  49637. };
  49638. /**
  49639. * Moves the cursor by the step amount
  49640. * If the step amount is greater than one, an exception is thrown
  49641. * @param step The amount to move the cursor
  49642. * @returns This path cursor
  49643. */
  49644. PathCursor.prototype.move = function (step) {
  49645. if (Math.abs(step) > 1) {
  49646. throw "step size should be less than 1.";
  49647. }
  49648. this.value += step;
  49649. this.ensureLimits();
  49650. this.raiseOnChange();
  49651. return this;
  49652. };
  49653. /**
  49654. * Ensures that the value is limited between zero and one
  49655. * @returns This path cursor
  49656. */
  49657. PathCursor.prototype.ensureLimits = function () {
  49658. while (this.value > 1) {
  49659. this.value -= 1;
  49660. }
  49661. while (this.value < 0) {
  49662. this.value += 1;
  49663. }
  49664. return this;
  49665. };
  49666. /**
  49667. * Runs onchange callbacks on change (used by the animation engine)
  49668. * @returns This path cursor
  49669. */
  49670. PathCursor.prototype.raiseOnChange = function () {
  49671. var _this = this;
  49672. this._onchange.forEach(function (f) { return f(_this); });
  49673. return this;
  49674. };
  49675. /**
  49676. * Executes a function on change
  49677. * @param f A path cursor onchange callback
  49678. * @returns This path cursor
  49679. */
  49680. PathCursor.prototype.onchange = function (f) {
  49681. this._onchange.push(f);
  49682. return this;
  49683. };
  49684. return PathCursor;
  49685. }());
  49686. BABYLON.PathCursor = PathCursor;
  49687. /**
  49688. * Enum for the animation key frame interpolation type
  49689. */
  49690. var AnimationKeyInterpolation;
  49691. (function (AnimationKeyInterpolation) {
  49692. /**
  49693. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49694. */
  49695. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49696. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49697. /**
  49698. * Class used to store any kind of animation
  49699. */
  49700. var Animation = /** @class */ (function () {
  49701. /**
  49702. * Initializes the animation
  49703. * @param name Name of the animation
  49704. * @param targetProperty Property to animate
  49705. * @param framePerSecond The frames per second of the animation
  49706. * @param dataType The data type of the animation
  49707. * @param loopMode The loop mode of the animation
  49708. * @param enableBlendings Specifies if blending should be enabled
  49709. */
  49710. function Animation(
  49711. /**Name of the animation */
  49712. name,
  49713. /**Property to animate */
  49714. targetProperty,
  49715. /**The frames per second of the animation */
  49716. framePerSecond,
  49717. /**The data type of the animation */
  49718. dataType,
  49719. /**The loop mode of the animation */
  49720. loopMode,
  49721. /**Specifies if blending should be enabled */
  49722. enableBlending) {
  49723. this.name = name;
  49724. this.targetProperty = targetProperty;
  49725. this.framePerSecond = framePerSecond;
  49726. this.dataType = dataType;
  49727. this.loopMode = loopMode;
  49728. this.enableBlending = enableBlending;
  49729. /**
  49730. * @hidden Internal use only
  49731. */
  49732. this._runtimeAnimations = new Array();
  49733. /**
  49734. * The set of event that will be linked to this animation
  49735. */
  49736. this._events = new Array();
  49737. /**
  49738. * Stores the blending speed of the animation
  49739. */
  49740. this.blendingSpeed = 0.01;
  49741. /**
  49742. * Stores the animation ranges for the animation
  49743. */
  49744. this._ranges = {};
  49745. this.targetPropertyPath = targetProperty.split(".");
  49746. this.dataType = dataType;
  49747. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49748. }
  49749. /**
  49750. * @hidden Internal use
  49751. */
  49752. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49753. var dataType = undefined;
  49754. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49755. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49756. }
  49757. else if (from instanceof BABYLON.Quaternion) {
  49758. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49759. }
  49760. else if (from instanceof BABYLON.Vector3) {
  49761. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49762. }
  49763. else if (from instanceof BABYLON.Vector2) {
  49764. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49765. }
  49766. else if (from instanceof BABYLON.Color3) {
  49767. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49768. }
  49769. else if (from instanceof BABYLON.Size) {
  49770. dataType = Animation.ANIMATIONTYPE_SIZE;
  49771. }
  49772. if (dataType == undefined) {
  49773. return null;
  49774. }
  49775. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49776. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49777. animation.setKeys(keys);
  49778. if (easingFunction !== undefined) {
  49779. animation.setEasingFunction(easingFunction);
  49780. }
  49781. return animation;
  49782. };
  49783. /**
  49784. * Sets up an animation
  49785. * @param property The property to animate
  49786. * @param animationType The animation type to apply
  49787. * @param framePerSecond The frames per second of the animation
  49788. * @param easingFunction The easing function used in the animation
  49789. * @returns The created animation
  49790. */
  49791. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49792. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49793. animation.setEasingFunction(easingFunction);
  49794. return animation;
  49795. };
  49796. /**
  49797. * Create and start an animation on a node
  49798. * @param name defines the name of the global animation that will be run on all nodes
  49799. * @param node defines the root node where the animation will take place
  49800. * @param targetProperty defines property to animate
  49801. * @param framePerSecond defines the number of frame per second yo use
  49802. * @param totalFrame defines the number of frames in total
  49803. * @param from defines the initial value
  49804. * @param to defines the final value
  49805. * @param loopMode defines which loop mode you want to use (off by default)
  49806. * @param easingFunction defines the easing function to use (linear by default)
  49807. * @param onAnimationEnd defines the callback to call when animation end
  49808. * @returns the animatable created for this animation
  49809. */
  49810. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49811. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49812. if (!animation) {
  49813. return null;
  49814. }
  49815. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49816. };
  49817. /**
  49818. * Create and start an animation on a node and its descendants
  49819. * @param name defines the name of the global animation that will be run on all nodes
  49820. * @param node defines the root node where the animation will take place
  49821. * @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
  49822. * @param targetProperty defines property to animate
  49823. * @param framePerSecond defines the number of frame per second to use
  49824. * @param totalFrame defines the number of frames in total
  49825. * @param from defines the initial value
  49826. * @param to defines the final value
  49827. * @param loopMode defines which loop mode you want to use (off by default)
  49828. * @param easingFunction defines the easing function to use (linear by default)
  49829. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49830. * @returns the list of animatables created for all nodes
  49831. * @example https://www.babylonjs-playground.com/#MH0VLI
  49832. */
  49833. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49834. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49835. if (!animation) {
  49836. return null;
  49837. }
  49838. var scene = node.getScene();
  49839. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49840. };
  49841. /**
  49842. * Creates a new animation, merges it with the existing animations and starts it
  49843. * @param name Name of the animation
  49844. * @param node Node which contains the scene that begins the animations
  49845. * @param targetProperty Specifies which property to animate
  49846. * @param framePerSecond The frames per second of the animation
  49847. * @param totalFrame The total number of frames
  49848. * @param from The frame at the beginning of the animation
  49849. * @param to The frame at the end of the animation
  49850. * @param loopMode Specifies the loop mode of the animation
  49851. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49852. * @param onAnimationEnd Callback to run once the animation is complete
  49853. * @returns Nullable animation
  49854. */
  49855. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49856. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49857. if (!animation) {
  49858. return null;
  49859. }
  49860. node.animations.push(animation);
  49861. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49862. };
  49863. /**
  49864. * Transition property of an host to the target Value
  49865. * @param property The property to transition
  49866. * @param targetValue The target Value of the property
  49867. * @param host The object where the property to animate belongs
  49868. * @param scene Scene used to run the animation
  49869. * @param frameRate Framerate (in frame/s) to use
  49870. * @param transition The transition type we want to use
  49871. * @param duration The duration of the animation, in milliseconds
  49872. * @param onAnimationEnd Callback trigger at the end of the animation
  49873. * @returns Nullable animation
  49874. */
  49875. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49876. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49877. if (duration <= 0) {
  49878. host[property] = targetValue;
  49879. if (onAnimationEnd) {
  49880. onAnimationEnd();
  49881. }
  49882. return null;
  49883. }
  49884. var endFrame = frameRate * (duration / 1000);
  49885. transition.setKeys([{
  49886. frame: 0,
  49887. value: host[property].clone ? host[property].clone() : host[property]
  49888. },
  49889. {
  49890. frame: endFrame,
  49891. value: targetValue
  49892. }]);
  49893. if (!host.animations) {
  49894. host.animations = [];
  49895. }
  49896. host.animations.push(transition);
  49897. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49898. animation.onAnimationEnd = onAnimationEnd;
  49899. return animation;
  49900. };
  49901. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49902. /**
  49903. * Return the array of runtime animations currently using this animation
  49904. */
  49905. get: function () {
  49906. return this._runtimeAnimations;
  49907. },
  49908. enumerable: true,
  49909. configurable: true
  49910. });
  49911. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49912. /**
  49913. * Specifies if any of the runtime animations are currently running
  49914. */
  49915. get: function () {
  49916. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49917. var runtimeAnimation = _a[_i];
  49918. if (!runtimeAnimation.isStopped) {
  49919. return true;
  49920. }
  49921. }
  49922. return false;
  49923. },
  49924. enumerable: true,
  49925. configurable: true
  49926. });
  49927. // Methods
  49928. /**
  49929. * Converts the animation to a string
  49930. * @param fullDetails support for multiple levels of logging within scene loading
  49931. * @returns String form of the animation
  49932. */
  49933. Animation.prototype.toString = function (fullDetails) {
  49934. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49935. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49936. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49937. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49938. if (fullDetails) {
  49939. ret += ", Ranges: {";
  49940. var first = true;
  49941. for (var name in this._ranges) {
  49942. if (first) {
  49943. ret += ", ";
  49944. first = false;
  49945. }
  49946. ret += name;
  49947. }
  49948. ret += "}";
  49949. }
  49950. return ret;
  49951. };
  49952. /**
  49953. * Add an event to this animation
  49954. * @param event Event to add
  49955. */
  49956. Animation.prototype.addEvent = function (event) {
  49957. this._events.push(event);
  49958. };
  49959. /**
  49960. * Remove all events found at the given frame
  49961. * @param frame The frame to remove events from
  49962. */
  49963. Animation.prototype.removeEvents = function (frame) {
  49964. for (var index = 0; index < this._events.length; index++) {
  49965. if (this._events[index].frame === frame) {
  49966. this._events.splice(index, 1);
  49967. index--;
  49968. }
  49969. }
  49970. };
  49971. /**
  49972. * Retrieves all the events from the animation
  49973. * @returns Events from the animation
  49974. */
  49975. Animation.prototype.getEvents = function () {
  49976. return this._events;
  49977. };
  49978. /**
  49979. * Creates an animation range
  49980. * @param name Name of the animation range
  49981. * @param from Starting frame of the animation range
  49982. * @param to Ending frame of the animation
  49983. */
  49984. Animation.prototype.createRange = function (name, from, to) {
  49985. // check name not already in use; could happen for bones after serialized
  49986. if (!this._ranges[name]) {
  49987. this._ranges[name] = new AnimationRange(name, from, to);
  49988. }
  49989. };
  49990. /**
  49991. * Deletes an animation range by name
  49992. * @param name Name of the animation range to delete
  49993. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49994. */
  49995. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49996. if (deleteFrames === void 0) { deleteFrames = true; }
  49997. var range = this._ranges[name];
  49998. if (!range) {
  49999. return;
  50000. }
  50001. if (deleteFrames) {
  50002. var from = range.from;
  50003. var to = range.to;
  50004. // this loop MUST go high to low for multiple splices to work
  50005. for (var key = this._keys.length - 1; key >= 0; key--) {
  50006. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50007. this._keys.splice(key, 1);
  50008. }
  50009. }
  50010. }
  50011. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50012. };
  50013. /**
  50014. * Gets the animation range by name, or null if not defined
  50015. * @param name Name of the animation range
  50016. * @returns Nullable animation range
  50017. */
  50018. Animation.prototype.getRange = function (name) {
  50019. return this._ranges[name];
  50020. };
  50021. /**
  50022. * Gets the key frames from the animation
  50023. * @returns The key frames of the animation
  50024. */
  50025. Animation.prototype.getKeys = function () {
  50026. return this._keys;
  50027. };
  50028. /**
  50029. * Gets the highest frame rate of the animation
  50030. * @returns Highest frame rate of the animation
  50031. */
  50032. Animation.prototype.getHighestFrame = function () {
  50033. var ret = 0;
  50034. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50035. if (ret < this._keys[key].frame) {
  50036. ret = this._keys[key].frame;
  50037. }
  50038. }
  50039. return ret;
  50040. };
  50041. /**
  50042. * Gets the easing function of the animation
  50043. * @returns Easing function of the animation
  50044. */
  50045. Animation.prototype.getEasingFunction = function () {
  50046. return this._easingFunction;
  50047. };
  50048. /**
  50049. * Sets the easing function of the animation
  50050. * @param easingFunction A custom mathematical formula for animation
  50051. */
  50052. Animation.prototype.setEasingFunction = function (easingFunction) {
  50053. this._easingFunction = easingFunction;
  50054. };
  50055. /**
  50056. * Interpolates a scalar linearly
  50057. * @param startValue Start value of the animation curve
  50058. * @param endValue End value of the animation curve
  50059. * @param gradient Scalar amount to interpolate
  50060. * @returns Interpolated scalar value
  50061. */
  50062. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50063. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50064. };
  50065. /**
  50066. * Interpolates a scalar cubically
  50067. * @param startValue Start value of the animation curve
  50068. * @param outTangent End tangent of the animation
  50069. * @param endValue End value of the animation curve
  50070. * @param inTangent Start tangent of the animation curve
  50071. * @param gradient Scalar amount to interpolate
  50072. * @returns Interpolated scalar value
  50073. */
  50074. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50075. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50076. };
  50077. /**
  50078. * Interpolates a quaternion using a spherical linear interpolation
  50079. * @param startValue Start value of the animation curve
  50080. * @param endValue End value of the animation curve
  50081. * @param gradient Scalar amount to interpolate
  50082. * @returns Interpolated quaternion value
  50083. */
  50084. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50085. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50086. };
  50087. /**
  50088. * Interpolates a quaternion cubically
  50089. * @param startValue Start value of the animation curve
  50090. * @param outTangent End tangent of the animation curve
  50091. * @param endValue End value of the animation curve
  50092. * @param inTangent Start tangent of the animation curve
  50093. * @param gradient Scalar amount to interpolate
  50094. * @returns Interpolated quaternion value
  50095. */
  50096. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50097. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50098. };
  50099. /**
  50100. * Interpolates a Vector3 linearl
  50101. * @param startValue Start value of the animation curve
  50102. * @param endValue End value of the animation curve
  50103. * @param gradient Scalar amount to interpolate
  50104. * @returns Interpolated scalar value
  50105. */
  50106. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50107. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50108. };
  50109. /**
  50110. * Interpolates a Vector3 cubically
  50111. * @param startValue Start value of the animation curve
  50112. * @param outTangent End tangent of the animation
  50113. * @param endValue End value of the animation curve
  50114. * @param inTangent Start tangent of the animation curve
  50115. * @param gradient Scalar amount to interpolate
  50116. * @returns InterpolatedVector3 value
  50117. */
  50118. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50119. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50120. };
  50121. /**
  50122. * Interpolates a Vector2 linearly
  50123. * @param startValue Start value of the animation curve
  50124. * @param endValue End value of the animation curve
  50125. * @param gradient Scalar amount to interpolate
  50126. * @returns Interpolated Vector2 value
  50127. */
  50128. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50129. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50130. };
  50131. /**
  50132. * Interpolates a Vector2 cubically
  50133. * @param startValue Start value of the animation curve
  50134. * @param outTangent End tangent of the animation
  50135. * @param endValue End value of the animation curve
  50136. * @param inTangent Start tangent of the animation curve
  50137. * @param gradient Scalar amount to interpolate
  50138. * @returns Interpolated Vector2 value
  50139. */
  50140. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50141. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50142. };
  50143. /**
  50144. * Interpolates a size linearly
  50145. * @param startValue Start value of the animation curve
  50146. * @param endValue End value of the animation curve
  50147. * @param gradient Scalar amount to interpolate
  50148. * @returns Interpolated Size value
  50149. */
  50150. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50151. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50152. };
  50153. /**
  50154. * Interpolates a Color3 linearly
  50155. * @param startValue Start value of the animation curve
  50156. * @param endValue End value of the animation curve
  50157. * @param gradient Scalar amount to interpolate
  50158. * @returns Interpolated Color3 value
  50159. */
  50160. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50161. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50162. };
  50163. /**
  50164. * @hidden Internal use only
  50165. */
  50166. Animation.prototype._getKeyValue = function (value) {
  50167. if (typeof value === "function") {
  50168. return value();
  50169. }
  50170. return value;
  50171. };
  50172. /**
  50173. * @hidden Internal use only
  50174. */
  50175. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50176. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50177. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50178. }
  50179. var keys = this.getKeys();
  50180. // Try to get a hash to find the right key
  50181. 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));
  50182. if (keys[startKeyIndex].frame >= currentFrame) {
  50183. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50184. startKeyIndex--;
  50185. }
  50186. }
  50187. for (var key = startKeyIndex; key < keys.length; key++) {
  50188. var endKey = keys[key + 1];
  50189. if (endKey.frame >= currentFrame) {
  50190. var startKey = keys[key];
  50191. var startValue = this._getKeyValue(startKey.value);
  50192. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50193. return startValue;
  50194. }
  50195. var endValue = this._getKeyValue(endKey.value);
  50196. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50197. var frameDelta = endKey.frame - startKey.frame;
  50198. // gradient : percent of currentFrame between the frame inf and the frame sup
  50199. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50200. // check for easingFunction and correction of gradient
  50201. var easingFunction = this.getEasingFunction();
  50202. if (easingFunction != null) {
  50203. gradient = easingFunction.ease(gradient);
  50204. }
  50205. switch (this.dataType) {
  50206. // Float
  50207. case Animation.ANIMATIONTYPE_FLOAT:
  50208. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50209. switch (loopMode) {
  50210. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50211. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50212. return floatValue;
  50213. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50214. return offsetValue * repeatCount + floatValue;
  50215. }
  50216. break;
  50217. // Quaternion
  50218. case Animation.ANIMATIONTYPE_QUATERNION:
  50219. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50220. switch (loopMode) {
  50221. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50222. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50223. return quatValue;
  50224. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50225. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50226. }
  50227. return quatValue;
  50228. // Vector3
  50229. case Animation.ANIMATIONTYPE_VECTOR3:
  50230. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50231. switch (loopMode) {
  50232. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50233. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50234. return vec3Value;
  50235. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50236. return vec3Value.add(offsetValue.scale(repeatCount));
  50237. }
  50238. // Vector2
  50239. case Animation.ANIMATIONTYPE_VECTOR2:
  50240. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50241. switch (loopMode) {
  50242. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50243. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50244. return vec2Value;
  50245. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50246. return vec2Value.add(offsetValue.scale(repeatCount));
  50247. }
  50248. // Size
  50249. case Animation.ANIMATIONTYPE_SIZE:
  50250. switch (loopMode) {
  50251. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50252. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50253. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50254. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50255. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50256. }
  50257. // Color3
  50258. case Animation.ANIMATIONTYPE_COLOR3:
  50259. switch (loopMode) {
  50260. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50261. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50262. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50263. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50264. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50265. }
  50266. // Matrix
  50267. case Animation.ANIMATIONTYPE_MATRIX:
  50268. switch (loopMode) {
  50269. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50270. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50271. if (Animation.AllowMatricesInterpolation) {
  50272. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50273. }
  50274. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50275. return startValue;
  50276. }
  50277. default:
  50278. break;
  50279. }
  50280. break;
  50281. }
  50282. }
  50283. return this._getKeyValue(keys[keys.length - 1].value);
  50284. };
  50285. /**
  50286. * Defines the function to use to interpolate matrices
  50287. * @param startValue defines the start matrix
  50288. * @param endValue defines the end matrix
  50289. * @param gradient defines the gradient between both matrices
  50290. * @param result defines an optional target matrix where to store the interpolation
  50291. * @returns the interpolated matrix
  50292. */
  50293. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50294. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50295. if (result) {
  50296. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50297. return result;
  50298. }
  50299. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50300. }
  50301. if (result) {
  50302. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50303. return result;
  50304. }
  50305. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50306. };
  50307. /**
  50308. * Makes a copy of the animation
  50309. * @returns Cloned animation
  50310. */
  50311. Animation.prototype.clone = function () {
  50312. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50313. clone.enableBlending = this.enableBlending;
  50314. clone.blendingSpeed = this.blendingSpeed;
  50315. if (this._keys) {
  50316. clone.setKeys(this._keys);
  50317. }
  50318. if (this._ranges) {
  50319. clone._ranges = {};
  50320. for (var name in this._ranges) {
  50321. var range = this._ranges[name];
  50322. if (!range) {
  50323. continue;
  50324. }
  50325. clone._ranges[name] = range.clone();
  50326. }
  50327. }
  50328. return clone;
  50329. };
  50330. /**
  50331. * Sets the key frames of the animation
  50332. * @param values The animation key frames to set
  50333. */
  50334. Animation.prototype.setKeys = function (values) {
  50335. this._keys = values.slice(0);
  50336. };
  50337. /**
  50338. * Serializes the animation to an object
  50339. * @returns Serialized object
  50340. */
  50341. Animation.prototype.serialize = function () {
  50342. var serializationObject = {};
  50343. serializationObject.name = this.name;
  50344. serializationObject.property = this.targetProperty;
  50345. serializationObject.framePerSecond = this.framePerSecond;
  50346. serializationObject.dataType = this.dataType;
  50347. serializationObject.loopBehavior = this.loopMode;
  50348. serializationObject.enableBlending = this.enableBlending;
  50349. serializationObject.blendingSpeed = this.blendingSpeed;
  50350. var dataType = this.dataType;
  50351. serializationObject.keys = [];
  50352. var keys = this.getKeys();
  50353. for (var index = 0; index < keys.length; index++) {
  50354. var animationKey = keys[index];
  50355. var key = {};
  50356. key.frame = animationKey.frame;
  50357. switch (dataType) {
  50358. case Animation.ANIMATIONTYPE_FLOAT:
  50359. key.values = [animationKey.value];
  50360. break;
  50361. case Animation.ANIMATIONTYPE_QUATERNION:
  50362. case Animation.ANIMATIONTYPE_MATRIX:
  50363. case Animation.ANIMATIONTYPE_VECTOR3:
  50364. case Animation.ANIMATIONTYPE_COLOR3:
  50365. key.values = animationKey.value.asArray();
  50366. break;
  50367. }
  50368. serializationObject.keys.push(key);
  50369. }
  50370. serializationObject.ranges = [];
  50371. for (var name in this._ranges) {
  50372. var source = this._ranges[name];
  50373. if (!source) {
  50374. continue;
  50375. }
  50376. var range = {};
  50377. range.name = name;
  50378. range.from = source.from;
  50379. range.to = source.to;
  50380. serializationObject.ranges.push(range);
  50381. }
  50382. return serializationObject;
  50383. };
  50384. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50385. /**
  50386. * Get the float animation type
  50387. */
  50388. get: function () {
  50389. return Animation._ANIMATIONTYPE_FLOAT;
  50390. },
  50391. enumerable: true,
  50392. configurable: true
  50393. });
  50394. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50395. /**
  50396. * Get the Vector3 animation type
  50397. */
  50398. get: function () {
  50399. return Animation._ANIMATIONTYPE_VECTOR3;
  50400. },
  50401. enumerable: true,
  50402. configurable: true
  50403. });
  50404. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50405. /**
  50406. * Get the Vector2 animation type
  50407. */
  50408. get: function () {
  50409. return Animation._ANIMATIONTYPE_VECTOR2;
  50410. },
  50411. enumerable: true,
  50412. configurable: true
  50413. });
  50414. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50415. /**
  50416. * Get the Size animation type
  50417. */
  50418. get: function () {
  50419. return Animation._ANIMATIONTYPE_SIZE;
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50425. /**
  50426. * Get the Quaternion animation type
  50427. */
  50428. get: function () {
  50429. return Animation._ANIMATIONTYPE_QUATERNION;
  50430. },
  50431. enumerable: true,
  50432. configurable: true
  50433. });
  50434. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50435. /**
  50436. * Get the Matrix animation type
  50437. */
  50438. get: function () {
  50439. return Animation._ANIMATIONTYPE_MATRIX;
  50440. },
  50441. enumerable: true,
  50442. configurable: true
  50443. });
  50444. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50445. /**
  50446. * Get the Color3 animation type
  50447. */
  50448. get: function () {
  50449. return Animation._ANIMATIONTYPE_COLOR3;
  50450. },
  50451. enumerable: true,
  50452. configurable: true
  50453. });
  50454. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50455. /**
  50456. * Get the Relative Loop Mode
  50457. */
  50458. get: function () {
  50459. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50460. },
  50461. enumerable: true,
  50462. configurable: true
  50463. });
  50464. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50465. /**
  50466. * Get the Cycle Loop Mode
  50467. */
  50468. get: function () {
  50469. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50470. },
  50471. enumerable: true,
  50472. configurable: true
  50473. });
  50474. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50475. /**
  50476. * Get the Constant Loop Mode
  50477. */
  50478. get: function () {
  50479. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50480. },
  50481. enumerable: true,
  50482. configurable: true
  50483. });
  50484. /** @hidden */
  50485. Animation._UniversalLerp = function (left, right, amount) {
  50486. var constructor = left.constructor;
  50487. if (constructor.Lerp) { // Lerp supported
  50488. return constructor.Lerp(left, right, amount);
  50489. }
  50490. else if (constructor.Slerp) { // Slerp supported
  50491. return constructor.Slerp(left, right, amount);
  50492. }
  50493. else if (left.toFixed) { // Number
  50494. return left * (1.0 - amount) + amount * right;
  50495. }
  50496. else { // Blending not supported
  50497. return right;
  50498. }
  50499. };
  50500. /**
  50501. * Parses an animation object and creates an animation
  50502. * @param parsedAnimation Parsed animation object
  50503. * @returns Animation object
  50504. */
  50505. Animation.Parse = function (parsedAnimation) {
  50506. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50507. var dataType = parsedAnimation.dataType;
  50508. var keys = [];
  50509. var data;
  50510. var index;
  50511. if (parsedAnimation.enableBlending) {
  50512. animation.enableBlending = parsedAnimation.enableBlending;
  50513. }
  50514. if (parsedAnimation.blendingSpeed) {
  50515. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50516. }
  50517. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50518. var key = parsedAnimation.keys[index];
  50519. var inTangent;
  50520. var outTangent;
  50521. switch (dataType) {
  50522. case Animation.ANIMATIONTYPE_FLOAT:
  50523. data = key.values[0];
  50524. if (key.values.length >= 1) {
  50525. inTangent = key.values[1];
  50526. }
  50527. if (key.values.length >= 2) {
  50528. outTangent = key.values[2];
  50529. }
  50530. break;
  50531. case Animation.ANIMATIONTYPE_QUATERNION:
  50532. data = BABYLON.Quaternion.FromArray(key.values);
  50533. if (key.values.length >= 8) {
  50534. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50535. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50536. inTangent = _inTangent;
  50537. }
  50538. }
  50539. if (key.values.length >= 12) {
  50540. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50541. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50542. outTangent = _outTangent;
  50543. }
  50544. }
  50545. break;
  50546. case Animation.ANIMATIONTYPE_MATRIX:
  50547. data = BABYLON.Matrix.FromArray(key.values);
  50548. break;
  50549. case Animation.ANIMATIONTYPE_COLOR3:
  50550. data = BABYLON.Color3.FromArray(key.values);
  50551. break;
  50552. case Animation.ANIMATIONTYPE_VECTOR3:
  50553. default:
  50554. data = BABYLON.Vector3.FromArray(key.values);
  50555. break;
  50556. }
  50557. var keyData = {};
  50558. keyData.frame = key.frame;
  50559. keyData.value = data;
  50560. if (inTangent != undefined) {
  50561. keyData.inTangent = inTangent;
  50562. }
  50563. if (outTangent != undefined) {
  50564. keyData.outTangent = outTangent;
  50565. }
  50566. keys.push(keyData);
  50567. }
  50568. animation.setKeys(keys);
  50569. if (parsedAnimation.ranges) {
  50570. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50571. data = parsedAnimation.ranges[index];
  50572. animation.createRange(data.name, data.from, data.to);
  50573. }
  50574. }
  50575. return animation;
  50576. };
  50577. /**
  50578. * Appends the serialized animations from the source animations
  50579. * @param source Source containing the animations
  50580. * @param destination Target to store the animations
  50581. */
  50582. Animation.AppendSerializedAnimations = function (source, destination) {
  50583. if (source.animations) {
  50584. destination.animations = [];
  50585. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50586. var animation = source.animations[animationIndex];
  50587. destination.animations.push(animation.serialize());
  50588. }
  50589. }
  50590. };
  50591. /**
  50592. * Use matrix interpolation instead of using direct key value when animating matrices
  50593. */
  50594. Animation.AllowMatricesInterpolation = false;
  50595. /**
  50596. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50597. */
  50598. Animation.AllowMatrixDecomposeForInterpolation = true;
  50599. // Statics
  50600. /**
  50601. * Float animation type
  50602. */
  50603. Animation._ANIMATIONTYPE_FLOAT = 0;
  50604. /**
  50605. * Vector3 animation type
  50606. */
  50607. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50608. /**
  50609. * Quaternion animation type
  50610. */
  50611. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50612. /**
  50613. * Matrix animation type
  50614. */
  50615. Animation._ANIMATIONTYPE_MATRIX = 3;
  50616. /**
  50617. * Color3 animation type
  50618. */
  50619. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50620. /**
  50621. * Vector2 animation type
  50622. */
  50623. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50624. /**
  50625. * Size animation type
  50626. */
  50627. Animation._ANIMATIONTYPE_SIZE = 6;
  50628. /**
  50629. * Relative Loop Mode
  50630. */
  50631. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50632. /**
  50633. * Cycle Loop Mode
  50634. */
  50635. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50636. /**
  50637. * Constant Loop Mode
  50638. */
  50639. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50640. return Animation;
  50641. }());
  50642. BABYLON.Animation = Animation;
  50643. })(BABYLON || (BABYLON = {}));
  50644. //# sourceMappingURL=babylon.animation.js.map
  50645. var BABYLON;
  50646. (function (BABYLON) {
  50647. /**
  50648. * This class defines the direct association between an animation and a target
  50649. */
  50650. var TargetedAnimation = /** @class */ (function () {
  50651. function TargetedAnimation() {
  50652. }
  50653. return TargetedAnimation;
  50654. }());
  50655. BABYLON.TargetedAnimation = TargetedAnimation;
  50656. /**
  50657. * Use this class to create coordinated animations on multiple targets
  50658. */
  50659. var AnimationGroup = /** @class */ (function () {
  50660. function AnimationGroup(name, scene) {
  50661. if (scene === void 0) { scene = null; }
  50662. this.name = name;
  50663. this._targetedAnimations = new Array();
  50664. this._animatables = new Array();
  50665. this._from = Number.MAX_VALUE;
  50666. this._to = -Number.MAX_VALUE;
  50667. this._speedRatio = 1;
  50668. this.onAnimationEndObservable = new BABYLON.Observable();
  50669. /**
  50670. * This observable will notify when all animations have ended.
  50671. */
  50672. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50673. /**
  50674. * This observable will notify when all animations have paused.
  50675. */
  50676. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50677. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50678. this._scene.animationGroups.push(this);
  50679. }
  50680. Object.defineProperty(AnimationGroup.prototype, "from", {
  50681. /**
  50682. * Gets the first frame
  50683. */
  50684. get: function () {
  50685. return this._from;
  50686. },
  50687. enumerable: true,
  50688. configurable: true
  50689. });
  50690. Object.defineProperty(AnimationGroup.prototype, "to", {
  50691. /**
  50692. * Gets the last frame
  50693. */
  50694. get: function () {
  50695. return this._to;
  50696. },
  50697. enumerable: true,
  50698. configurable: true
  50699. });
  50700. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50701. /**
  50702. * Define if the animations are started
  50703. */
  50704. get: function () {
  50705. return this._isStarted;
  50706. },
  50707. enumerable: true,
  50708. configurable: true
  50709. });
  50710. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50711. /**
  50712. * Gets or sets the speed ratio to use for all animations
  50713. */
  50714. get: function () {
  50715. return this._speedRatio;
  50716. },
  50717. /**
  50718. * Gets or sets the speed ratio to use for all animations
  50719. */
  50720. set: function (value) {
  50721. if (this._speedRatio === value) {
  50722. return;
  50723. }
  50724. this._speedRatio = value;
  50725. for (var index = 0; index < this._animatables.length; index++) {
  50726. var animatable = this._animatables[index];
  50727. animatable.speedRatio = this._speedRatio;
  50728. }
  50729. },
  50730. enumerable: true,
  50731. configurable: true
  50732. });
  50733. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50734. /**
  50735. * Gets the targeted animations for this animation group
  50736. */
  50737. get: function () {
  50738. return this._targetedAnimations;
  50739. },
  50740. enumerable: true,
  50741. configurable: true
  50742. });
  50743. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50744. /**
  50745. * returning the list of animatables controlled by this animation group.
  50746. */
  50747. get: function () {
  50748. return this._animatables;
  50749. },
  50750. enumerable: true,
  50751. configurable: true
  50752. });
  50753. /**
  50754. * Add an animation (with its target) in the group
  50755. * @param animation defines the animation we want to add
  50756. * @param target defines the target of the animation
  50757. * @returns the {BABYLON.TargetedAnimation} object
  50758. */
  50759. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50760. var targetedAnimation = {
  50761. animation: animation,
  50762. target: target
  50763. };
  50764. var keys = animation.getKeys();
  50765. if (this._from > keys[0].frame) {
  50766. this._from = keys[0].frame;
  50767. }
  50768. if (this._to < keys[keys.length - 1].frame) {
  50769. this._to = keys[keys.length - 1].frame;
  50770. }
  50771. this._targetedAnimations.push(targetedAnimation);
  50772. return targetedAnimation;
  50773. };
  50774. /**
  50775. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50776. * It can add constant keys at begin or end
  50777. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50778. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50779. */
  50780. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50781. if (beginFrame === void 0) { beginFrame = null; }
  50782. if (endFrame === void 0) { endFrame = null; }
  50783. if (beginFrame == null)
  50784. beginFrame = this._from;
  50785. if (endFrame == null)
  50786. endFrame = this._to;
  50787. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50788. var targetedAnimation = this._targetedAnimations[index];
  50789. var keys = targetedAnimation.animation.getKeys();
  50790. var startKey = keys[0];
  50791. var endKey = keys[keys.length - 1];
  50792. if (startKey.frame > beginFrame) {
  50793. var newKey = {
  50794. frame: beginFrame,
  50795. value: startKey.value,
  50796. inTangent: startKey.inTangent,
  50797. outTangent: startKey.outTangent,
  50798. interpolation: startKey.interpolation
  50799. };
  50800. keys.splice(0, 0, newKey);
  50801. }
  50802. if (endKey.frame < endFrame) {
  50803. var newKey = {
  50804. frame: endFrame,
  50805. value: endKey.value,
  50806. inTangent: endKey.outTangent,
  50807. outTangent: endKey.outTangent,
  50808. interpolation: endKey.interpolation
  50809. };
  50810. keys.push(newKey);
  50811. }
  50812. }
  50813. this._from = beginFrame;
  50814. this._to = endFrame;
  50815. return this;
  50816. };
  50817. /**
  50818. * Start all animations on given targets
  50819. * @param loop defines if animations must loop
  50820. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50821. * @param from defines the from key (optional)
  50822. * @param to defines the to key (optional)
  50823. * @returns the current animation group
  50824. */
  50825. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50826. var _this = this;
  50827. if (loop === void 0) { loop = false; }
  50828. if (speedRatio === void 0) { speedRatio = 1; }
  50829. if (this._isStarted || this._targetedAnimations.length === 0) {
  50830. return this;
  50831. }
  50832. var _loop_1 = function (targetedAnimation) {
  50833. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50834. animatable.onAnimationEnd = function () {
  50835. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50836. _this._checkAnimationGroupEnded(animatable);
  50837. };
  50838. this_1._animatables.push(animatable);
  50839. };
  50840. var this_1 = this;
  50841. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50842. var targetedAnimation = _a[_i];
  50843. _loop_1(targetedAnimation);
  50844. }
  50845. this._speedRatio = speedRatio;
  50846. this._isStarted = true;
  50847. return this;
  50848. };
  50849. /**
  50850. * Pause all animations
  50851. */
  50852. AnimationGroup.prototype.pause = function () {
  50853. if (!this._isStarted) {
  50854. return this;
  50855. }
  50856. for (var index = 0; index < this._animatables.length; index++) {
  50857. var animatable = this._animatables[index];
  50858. animatable.pause();
  50859. }
  50860. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50861. return this;
  50862. };
  50863. /**
  50864. * Play all animations to initial state
  50865. * This function will start() the animations if they were not started or will restart() them if they were paused
  50866. * @param loop defines if animations must loop
  50867. */
  50868. AnimationGroup.prototype.play = function (loop) {
  50869. // only if all animatables are ready and exist
  50870. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50871. if (loop !== undefined) {
  50872. for (var index = 0; index < this._animatables.length; index++) {
  50873. var animatable = this._animatables[index];
  50874. animatable.loopAnimation = loop;
  50875. }
  50876. }
  50877. this.restart();
  50878. }
  50879. else {
  50880. this.stop();
  50881. this.start(loop, this._speedRatio);
  50882. }
  50883. return this;
  50884. };
  50885. /**
  50886. * Reset all animations to initial state
  50887. */
  50888. AnimationGroup.prototype.reset = function () {
  50889. if (!this._isStarted) {
  50890. return this;
  50891. }
  50892. for (var index = 0; index < this._animatables.length; index++) {
  50893. var animatable = this._animatables[index];
  50894. animatable.reset();
  50895. }
  50896. return this;
  50897. };
  50898. /**
  50899. * Restart animations from key 0
  50900. */
  50901. AnimationGroup.prototype.restart = function () {
  50902. if (!this._isStarted) {
  50903. return this;
  50904. }
  50905. for (var index = 0; index < this._animatables.length; index++) {
  50906. var animatable = this._animatables[index];
  50907. animatable.restart();
  50908. }
  50909. return this;
  50910. };
  50911. /**
  50912. * Stop all animations
  50913. */
  50914. AnimationGroup.prototype.stop = function () {
  50915. if (!this._isStarted) {
  50916. return this;
  50917. }
  50918. var list = this._animatables.slice();
  50919. for (var index = 0; index < list.length; index++) {
  50920. list[index].stop();
  50921. }
  50922. this._isStarted = false;
  50923. return this;
  50924. };
  50925. /**
  50926. * Set animation weight for all animatables
  50927. * @param weight defines the weight to use
  50928. * @return the animationGroup
  50929. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50930. */
  50931. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50932. for (var index = 0; index < this._animatables.length; index++) {
  50933. var animatable = this._animatables[index];
  50934. animatable.weight = weight;
  50935. }
  50936. return this;
  50937. };
  50938. /**
  50939. * Synchronize and normalize all animatables with a source animatable
  50940. * @param root defines the root animatable to synchronize with
  50941. * @return the animationGroup
  50942. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50943. */
  50944. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50945. for (var index = 0; index < this._animatables.length; index++) {
  50946. var animatable = this._animatables[index];
  50947. animatable.syncWith(root);
  50948. }
  50949. return this;
  50950. };
  50951. /**
  50952. * Goes to a specific frame in this animation group
  50953. * @param frame the frame number to go to
  50954. * @return the animationGroup
  50955. */
  50956. AnimationGroup.prototype.goToFrame = function (frame) {
  50957. if (!this._isStarted) {
  50958. return this;
  50959. }
  50960. for (var index = 0; index < this._animatables.length; index++) {
  50961. var animatable = this._animatables[index];
  50962. animatable.goToFrame(frame);
  50963. }
  50964. return this;
  50965. };
  50966. /**
  50967. * Dispose all associated resources
  50968. */
  50969. AnimationGroup.prototype.dispose = function () {
  50970. this._targetedAnimations = [];
  50971. this._animatables = [];
  50972. var index = this._scene.animationGroups.indexOf(this);
  50973. if (index > -1) {
  50974. this._scene.animationGroups.splice(index, 1);
  50975. }
  50976. };
  50977. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50978. // animatable should be taken out of the array
  50979. var idx = this._animatables.indexOf(animatable);
  50980. if (idx > -1) {
  50981. this._animatables.splice(idx, 1);
  50982. }
  50983. // all animatables were removed? animation group ended!
  50984. if (this._animatables.length === 0) {
  50985. this._isStarted = false;
  50986. this.onAnimationGroupEndObservable.notifyObservers(this);
  50987. }
  50988. };
  50989. return AnimationGroup;
  50990. }());
  50991. BABYLON.AnimationGroup = AnimationGroup;
  50992. })(BABYLON || (BABYLON = {}));
  50993. //# sourceMappingURL=babylon.animationGroup.js.map
  50994. var BABYLON;
  50995. (function (BABYLON) {
  50996. /**
  50997. * Defines a runtime animation
  50998. */
  50999. var RuntimeAnimation = /** @class */ (function () {
  51000. /**
  51001. * Create a new RuntimeAnimation object
  51002. * @param target defines the target of the animation
  51003. * @param animation defines the source animation object
  51004. * @param scene defines the hosting scene
  51005. * @param host defines the initiating Animatable
  51006. */
  51007. function RuntimeAnimation(target, animation, scene, host) {
  51008. var _this = this;
  51009. this._events = new Array();
  51010. /**
  51011. * The current frame of the runtime animation
  51012. */
  51013. this._currentFrame = 0;
  51014. /**
  51015. * The original value of the runtime animation
  51016. */
  51017. this._originalValue = new Array();
  51018. /**
  51019. * The offsets cache of the runtime animation
  51020. */
  51021. this._offsetsCache = {};
  51022. /**
  51023. * The high limits cache of the runtime animation
  51024. */
  51025. this._highLimitsCache = {};
  51026. /**
  51027. * Specifies if the runtime animation has been stopped
  51028. */
  51029. this._stopped = false;
  51030. /**
  51031. * The blending factor of the runtime animation
  51032. */
  51033. this._blendingFactor = 0;
  51034. /**
  51035. * The target path of the runtime animation
  51036. */
  51037. this._targetPath = "";
  51038. /**
  51039. * The weight of the runtime animation
  51040. */
  51041. this._weight = 1.0;
  51042. /**
  51043. * The ratio offset of the runtime animation
  51044. */
  51045. this._ratioOffset = 0;
  51046. /**
  51047. * The previous delay of the runtime animation
  51048. */
  51049. this._previousDelay = 0;
  51050. /**
  51051. * The previous ratio of the runtime animation
  51052. */
  51053. this._previousRatio = 0;
  51054. this._animation = animation;
  51055. this._target = target;
  51056. this._scene = scene;
  51057. this._host = host;
  51058. animation._runtimeAnimations.push(this);
  51059. // Cloning events locally
  51060. var events = animation.getEvents();
  51061. if (events && events.length > 0) {
  51062. events.forEach(function (e) {
  51063. _this._events.push(e._clone());
  51064. });
  51065. }
  51066. }
  51067. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51068. /**
  51069. * Gets the current frame of the runtime animation
  51070. */
  51071. get: function () {
  51072. return this._currentFrame;
  51073. },
  51074. enumerable: true,
  51075. configurable: true
  51076. });
  51077. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51078. /**
  51079. * Gets the weight of the runtime animation
  51080. */
  51081. get: function () {
  51082. return this._weight;
  51083. },
  51084. enumerable: true,
  51085. configurable: true
  51086. });
  51087. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51088. /**
  51089. * Gets the current value of the runtime animation
  51090. */
  51091. get: function () {
  51092. return this._currentValue;
  51093. },
  51094. enumerable: true,
  51095. configurable: true
  51096. });
  51097. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51098. /**
  51099. * Gets the target path of the runtime animation
  51100. */
  51101. get: function () {
  51102. return this._targetPath;
  51103. },
  51104. enumerable: true,
  51105. configurable: true
  51106. });
  51107. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51108. /**
  51109. * Gets the actual target of the runtime animation
  51110. */
  51111. get: function () {
  51112. return this._activeTarget;
  51113. },
  51114. enumerable: true,
  51115. configurable: true
  51116. });
  51117. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51118. /**
  51119. * Gets the animation from the runtime animation
  51120. */
  51121. get: function () {
  51122. return this._animation;
  51123. },
  51124. enumerable: true,
  51125. configurable: true
  51126. });
  51127. /**
  51128. * Resets the runtime animation to the beginning
  51129. * @param restoreOriginal defines whether to restore the target property to the original value
  51130. */
  51131. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51132. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51133. if (restoreOriginal) {
  51134. if (this._target instanceof Array) {
  51135. var index = 0;
  51136. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51137. var target = _a[_i];
  51138. if (this._originalValue[index] !== undefined) {
  51139. this._setValue(target, this._originalValue[index], -1);
  51140. }
  51141. index++;
  51142. }
  51143. }
  51144. else {
  51145. if (this._originalValue[0] !== undefined) {
  51146. this._setValue(this._target, this._originalValue[0], -1);
  51147. }
  51148. }
  51149. }
  51150. this._offsetsCache = {};
  51151. this._highLimitsCache = {};
  51152. this._currentFrame = 0;
  51153. this._blendingFactor = 0;
  51154. this._originalValue = new Array();
  51155. // Events
  51156. for (var index = 0; index < this._events.length; index++) {
  51157. this._events[index].isDone = false;
  51158. }
  51159. };
  51160. /**
  51161. * Specifies if the runtime animation is stopped
  51162. * @returns Boolean specifying if the runtime animation is stopped
  51163. */
  51164. RuntimeAnimation.prototype.isStopped = function () {
  51165. return this._stopped;
  51166. };
  51167. /**
  51168. * Disposes of the runtime animation
  51169. */
  51170. RuntimeAnimation.prototype.dispose = function () {
  51171. var index = this._animation.runtimeAnimations.indexOf(this);
  51172. if (index > -1) {
  51173. this._animation.runtimeAnimations.splice(index, 1);
  51174. }
  51175. };
  51176. /**
  51177. * Interpolates the animation from the current frame
  51178. * @param currentFrame The frame to interpolate the animation to
  51179. * @param repeatCount The number of times that the animation should loop
  51180. * @param loopMode The type of looping mode to use
  51181. * @param offsetValue Animation offset value
  51182. * @param highLimitValue The high limit value
  51183. * @returns The interpolated value
  51184. */
  51185. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51186. this._currentFrame = currentFrame;
  51187. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51188. this._workValue = BABYLON.Matrix.Zero();
  51189. }
  51190. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51191. };
  51192. /**
  51193. * Apply the interpolated value to the target
  51194. * @param currentValue defines the value computed by the animation
  51195. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51196. */
  51197. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51198. if (weight === void 0) { weight = 1.0; }
  51199. if (this._target instanceof Array) {
  51200. var index = 0;
  51201. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51202. var target = _a[_i];
  51203. this._setValue(target, currentValue, weight, index);
  51204. index++;
  51205. }
  51206. }
  51207. else {
  51208. this._setValue(this._target, currentValue, weight);
  51209. }
  51210. };
  51211. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51212. if (targetIndex === void 0) { targetIndex = 0; }
  51213. // Set value
  51214. var path;
  51215. var destination;
  51216. var targetPropertyPath = this._animation.targetPropertyPath;
  51217. if (targetPropertyPath.length > 1) {
  51218. var property = target[targetPropertyPath[0]];
  51219. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51220. property = property[targetPropertyPath[index]];
  51221. }
  51222. path = targetPropertyPath[targetPropertyPath.length - 1];
  51223. destination = property;
  51224. }
  51225. else {
  51226. path = targetPropertyPath[0];
  51227. destination = target;
  51228. }
  51229. this._targetPath = path;
  51230. this._activeTarget = destination;
  51231. this._weight = weight;
  51232. if (this._originalValue[targetIndex] === undefined) {
  51233. var originalValue = void 0;
  51234. if (destination.getRestPose && path === "_matrix") { // For bones
  51235. originalValue = destination.getRestPose();
  51236. }
  51237. else {
  51238. originalValue = destination[path];
  51239. }
  51240. if (originalValue && originalValue.clone) {
  51241. this._originalValue[targetIndex] = originalValue.clone();
  51242. }
  51243. else {
  51244. this._originalValue[targetIndex] = originalValue;
  51245. }
  51246. }
  51247. // Blending
  51248. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51249. if (enableBlending && this._blendingFactor <= 1.0) {
  51250. if (!this._originalBlendValue) {
  51251. var originalValue = destination[path];
  51252. if (originalValue.clone) {
  51253. this._originalBlendValue = originalValue.clone();
  51254. }
  51255. else {
  51256. this._originalBlendValue = originalValue;
  51257. }
  51258. }
  51259. if (this._originalBlendValue.m) { // Matrix
  51260. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51261. if (this._currentValue) {
  51262. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51263. }
  51264. else {
  51265. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51266. }
  51267. }
  51268. else {
  51269. if (this._currentValue) {
  51270. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51271. }
  51272. else {
  51273. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51274. }
  51275. }
  51276. }
  51277. else {
  51278. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51279. }
  51280. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51281. this._blendingFactor += blendingSpeed;
  51282. }
  51283. else {
  51284. this._currentValue = currentValue;
  51285. }
  51286. if (weight !== -1.0) {
  51287. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51288. }
  51289. else {
  51290. destination[path] = this._currentValue;
  51291. }
  51292. if (target.markAsDirty) {
  51293. target.markAsDirty(this._animation.targetProperty);
  51294. }
  51295. };
  51296. /**
  51297. * Gets the loop pmode of the runtime animation
  51298. * @returns Loop Mode
  51299. */
  51300. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51301. if (this._target && this._target.animationPropertiesOverride) {
  51302. return this._target.animationPropertiesOverride.loopMode;
  51303. }
  51304. return this._animation.loopMode;
  51305. };
  51306. /**
  51307. * Move the current animation to a given frame
  51308. * @param frame defines the frame to move to
  51309. */
  51310. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51311. var keys = this._animation.getKeys();
  51312. if (frame < keys[0].frame) {
  51313. frame = keys[0].frame;
  51314. }
  51315. else if (frame > keys[keys.length - 1].frame) {
  51316. frame = keys[keys.length - 1].frame;
  51317. }
  51318. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51319. this.setValue(currentValue, -1);
  51320. };
  51321. /**
  51322. * @hidden Internal use only
  51323. */
  51324. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51325. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51326. this._ratioOffset = this._previousRatio - newRatio;
  51327. };
  51328. /**
  51329. * Execute the current animation
  51330. * @param delay defines the delay to add to the current frame
  51331. * @param from defines the lower bound of the animation range
  51332. * @param to defines the upper bound of the animation range
  51333. * @param loop defines if the current animation must loop
  51334. * @param speedRatio defines the current speed ratio
  51335. * @param weight defines the weight of the animation (default is -1 so no weight)
  51336. * @returns a boolean indicating if the animation is running
  51337. */
  51338. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51339. if (weight === void 0) { weight = -1.0; }
  51340. var targetPropertyPath = this._animation.targetPropertyPath;
  51341. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51342. this._stopped = true;
  51343. return false;
  51344. }
  51345. var returnValue = true;
  51346. var keys = this._animation.getKeys();
  51347. // Adding a start key at frame 0 if missing
  51348. if (keys[0].frame !== 0) {
  51349. var newKey = { frame: 0, value: keys[0].value };
  51350. keys.splice(0, 0, newKey);
  51351. }
  51352. // Adding a duplicate key when there is only one key at frame zero
  51353. else if (keys.length === 1) {
  51354. var newKey = { frame: 0.001, value: keys[0].value };
  51355. keys.push(newKey);
  51356. }
  51357. // Check limits
  51358. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51359. from = keys[0].frame;
  51360. }
  51361. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51362. to = keys[keys.length - 1].frame;
  51363. }
  51364. //to and from cannot be the same key
  51365. if (from === to) {
  51366. if (from > keys[0].frame) {
  51367. from--;
  51368. }
  51369. else if (to < keys[keys.length - 1].frame) {
  51370. to++;
  51371. }
  51372. }
  51373. // Compute ratio
  51374. var range = to - from;
  51375. var offsetValue;
  51376. // ratio represents the frame delta between from and to
  51377. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51378. var highLimitValue = 0;
  51379. this._previousDelay = delay;
  51380. this._previousRatio = ratio;
  51381. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51382. returnValue = false;
  51383. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51384. }
  51385. else {
  51386. // Get max value if required
  51387. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51388. var keyOffset = to.toString() + from.toString();
  51389. if (!this._offsetsCache[keyOffset]) {
  51390. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51391. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51392. switch (this._animation.dataType) {
  51393. // Float
  51394. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51395. this._offsetsCache[keyOffset] = toValue - fromValue;
  51396. break;
  51397. // Quaternion
  51398. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51399. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51400. break;
  51401. // Vector3
  51402. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51403. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51404. // Vector2
  51405. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51406. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51407. // Size
  51408. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51409. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51410. // Color3
  51411. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51412. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51413. default:
  51414. break;
  51415. }
  51416. this._highLimitsCache[keyOffset] = toValue;
  51417. }
  51418. highLimitValue = this._highLimitsCache[keyOffset];
  51419. offsetValue = this._offsetsCache[keyOffset];
  51420. }
  51421. }
  51422. if (offsetValue === undefined) {
  51423. switch (this._animation.dataType) {
  51424. // Float
  51425. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51426. offsetValue = 0;
  51427. break;
  51428. // Quaternion
  51429. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51430. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51431. break;
  51432. // Vector3
  51433. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51434. offsetValue = BABYLON.Vector3.Zero();
  51435. break;
  51436. // Vector2
  51437. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51438. offsetValue = BABYLON.Vector2.Zero();
  51439. break;
  51440. // Size
  51441. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51442. offsetValue = BABYLON.Size.Zero();
  51443. break;
  51444. // Color3
  51445. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51446. offsetValue = BABYLON.Color3.Black();
  51447. }
  51448. }
  51449. // Compute value
  51450. var repeatCount = (ratio / range) >> 0;
  51451. var currentFrame = returnValue ? from + ratio % range : to;
  51452. // Need to normalize?
  51453. if (this._host && this._host.syncRoot) {
  51454. var syncRoot = this._host.syncRoot;
  51455. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51456. currentFrame = from + (to - from) * hostNormalizedFrame;
  51457. }
  51458. // Reset events if looping
  51459. var events = this._events;
  51460. if (range > 0 && this.currentFrame > currentFrame ||
  51461. range < 0 && this.currentFrame < currentFrame) {
  51462. // Need to reset animation events
  51463. for (var index = 0; index < events.length; index++) {
  51464. if (!events[index].onlyOnce) {
  51465. // reset event, the animation is looping
  51466. events[index].isDone = false;
  51467. }
  51468. }
  51469. }
  51470. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51471. // Set value
  51472. this.setValue(currentValue, weight);
  51473. // Check events
  51474. for (var index = 0; index < events.length; index++) {
  51475. // Make sure current frame has passed event frame and that event frame is within the current range
  51476. // Also, handle both forward and reverse animations
  51477. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51478. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51479. var event = events[index];
  51480. if (!event.isDone) {
  51481. // If event should be done only once, remove it.
  51482. if (event.onlyOnce) {
  51483. events.splice(index, 1);
  51484. index--;
  51485. }
  51486. event.isDone = true;
  51487. event.action(currentFrame);
  51488. } // Don't do anything if the event has already be done.
  51489. }
  51490. }
  51491. if (!returnValue) {
  51492. this._stopped = true;
  51493. }
  51494. return returnValue;
  51495. };
  51496. return RuntimeAnimation;
  51497. }());
  51498. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51499. })(BABYLON || (BABYLON = {}));
  51500. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51501. var BABYLON;
  51502. (function (BABYLON) {
  51503. /**
  51504. * Class used to store an actual running animation
  51505. */
  51506. var Animatable = /** @class */ (function () {
  51507. /**
  51508. * Creates a new Animatable
  51509. * @param scene defines the hosting scene
  51510. * @param target defines the target object
  51511. * @param fromFrame defines the starting frame number (default is 0)
  51512. * @param toFrame defines the ending frame number (default is 100)
  51513. * @param loopAnimation defines if the animation must loop (default is false)
  51514. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51515. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51516. * @param animations defines a group of animation to add to the new Animatable
  51517. */
  51518. function Animatable(scene,
  51519. /** defines the target object */
  51520. target,
  51521. /** defines the starting frame number (default is 0) */
  51522. fromFrame,
  51523. /** defines the ending frame number (default is 100) */
  51524. toFrame,
  51525. /** defines if the animation must loop (default is false) */
  51526. loopAnimation, speedRatio,
  51527. /** defines a callback to call when animation ends if it is not looping */
  51528. onAnimationEnd, animations) {
  51529. if (fromFrame === void 0) { fromFrame = 0; }
  51530. if (toFrame === void 0) { toFrame = 100; }
  51531. if (loopAnimation === void 0) { loopAnimation = false; }
  51532. if (speedRatio === void 0) { speedRatio = 1.0; }
  51533. this.target = target;
  51534. this.fromFrame = fromFrame;
  51535. this.toFrame = toFrame;
  51536. this.loopAnimation = loopAnimation;
  51537. this.onAnimationEnd = onAnimationEnd;
  51538. this._localDelayOffset = null;
  51539. this._pausedDelay = null;
  51540. this._runtimeAnimations = new Array();
  51541. this._paused = false;
  51542. this._speedRatio = 1;
  51543. this._weight = -1.0;
  51544. /**
  51545. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51546. * This will only apply for non looping animation (default is true)
  51547. */
  51548. this.disposeOnEnd = true;
  51549. /**
  51550. * Gets a boolean indicating if the animation has started
  51551. */
  51552. this.animationStarted = false;
  51553. /**
  51554. * Observer raised when the animation ends
  51555. */
  51556. this.onAnimationEndObservable = new BABYLON.Observable();
  51557. this._scene = scene;
  51558. if (animations) {
  51559. this.appendAnimations(target, animations);
  51560. }
  51561. this._speedRatio = speedRatio;
  51562. scene._activeAnimatables.push(this);
  51563. }
  51564. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51565. /**
  51566. * Gets the root Animatable used to synchronize and normalize animations
  51567. */
  51568. get: function () {
  51569. return this._syncRoot;
  51570. },
  51571. enumerable: true,
  51572. configurable: true
  51573. });
  51574. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51575. /**
  51576. * Gets the current frame of the first RuntimeAnimation
  51577. * Used to synchronize Animatables
  51578. */
  51579. get: function () {
  51580. if (this._runtimeAnimations.length === 0) {
  51581. return 0;
  51582. }
  51583. return this._runtimeAnimations[0].currentFrame;
  51584. },
  51585. enumerable: true,
  51586. configurable: true
  51587. });
  51588. Object.defineProperty(Animatable.prototype, "weight", {
  51589. /**
  51590. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51591. */
  51592. get: function () {
  51593. return this._weight;
  51594. },
  51595. set: function (value) {
  51596. if (value === -1) { // -1 is ok and means no weight
  51597. this._weight = -1;
  51598. return;
  51599. }
  51600. // Else weight must be in [0, 1] range
  51601. this._weight = Math.min(Math.max(value, 0), 1.0);
  51602. },
  51603. enumerable: true,
  51604. configurable: true
  51605. });
  51606. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51607. /**
  51608. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51609. */
  51610. get: function () {
  51611. return this._speedRatio;
  51612. },
  51613. set: function (value) {
  51614. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51615. var animation = this._runtimeAnimations[index];
  51616. animation._prepareForSpeedRatioChange(value);
  51617. }
  51618. this._speedRatio = value;
  51619. },
  51620. enumerable: true,
  51621. configurable: true
  51622. });
  51623. // Methods
  51624. /**
  51625. * Synchronize and normalize current Animatable with a source Animatable
  51626. * This is useful when using animation weights and when animations are not of the same length
  51627. * @param root defines the root Animatable to synchronize with
  51628. * @returns the current Animatable
  51629. */
  51630. Animatable.prototype.syncWith = function (root) {
  51631. this._syncRoot = root;
  51632. if (root) {
  51633. // Make sure this animatable will animate after the root
  51634. var index = this._scene._activeAnimatables.indexOf(this);
  51635. if (index > -1) {
  51636. this._scene._activeAnimatables.splice(index, 1);
  51637. this._scene._activeAnimatables.push(this);
  51638. }
  51639. }
  51640. return this;
  51641. };
  51642. /**
  51643. * Gets the list of runtime animations
  51644. * @returns an array of RuntimeAnimation
  51645. */
  51646. Animatable.prototype.getAnimations = function () {
  51647. return this._runtimeAnimations;
  51648. };
  51649. /**
  51650. * Adds more animations to the current animatable
  51651. * @param target defines the target of the animations
  51652. * @param animations defines the new animations to add
  51653. */
  51654. Animatable.prototype.appendAnimations = function (target, animations) {
  51655. for (var index = 0; index < animations.length; index++) {
  51656. var animation = animations[index];
  51657. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51658. }
  51659. };
  51660. /**
  51661. * Gets the source animation for a specific property
  51662. * @param property defines the propertyu to look for
  51663. * @returns null or the source animation for the given property
  51664. */
  51665. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51666. var runtimeAnimations = this._runtimeAnimations;
  51667. for (var index = 0; index < runtimeAnimations.length; index++) {
  51668. if (runtimeAnimations[index].animation.targetProperty === property) {
  51669. return runtimeAnimations[index].animation;
  51670. }
  51671. }
  51672. return null;
  51673. };
  51674. /**
  51675. * Gets the runtime animation for a specific property
  51676. * @param property defines the propertyu to look for
  51677. * @returns null or the runtime animation for the given property
  51678. */
  51679. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51680. var runtimeAnimations = this._runtimeAnimations;
  51681. for (var index = 0; index < runtimeAnimations.length; index++) {
  51682. if (runtimeAnimations[index].animation.targetProperty === property) {
  51683. return runtimeAnimations[index];
  51684. }
  51685. }
  51686. return null;
  51687. };
  51688. /**
  51689. * Resets the animatable to its original state
  51690. */
  51691. Animatable.prototype.reset = function () {
  51692. var runtimeAnimations = this._runtimeAnimations;
  51693. for (var index = 0; index < runtimeAnimations.length; index++) {
  51694. runtimeAnimations[index].reset(true);
  51695. }
  51696. this._localDelayOffset = null;
  51697. this._pausedDelay = null;
  51698. };
  51699. /**
  51700. * Allows the animatable to blend with current running animations
  51701. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51702. * @param blendingSpeed defines the blending speed to use
  51703. */
  51704. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51705. var runtimeAnimations = this._runtimeAnimations;
  51706. for (var index = 0; index < runtimeAnimations.length; index++) {
  51707. runtimeAnimations[index].animation.enableBlending = true;
  51708. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51709. }
  51710. };
  51711. /**
  51712. * Disable animation blending
  51713. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51714. */
  51715. Animatable.prototype.disableBlending = function () {
  51716. var runtimeAnimations = this._runtimeAnimations;
  51717. for (var index = 0; index < runtimeAnimations.length; index++) {
  51718. runtimeAnimations[index].animation.enableBlending = false;
  51719. }
  51720. };
  51721. /**
  51722. * Jump directly to a given frame
  51723. * @param frame defines the frame to jump to
  51724. */
  51725. Animatable.prototype.goToFrame = function (frame) {
  51726. var runtimeAnimations = this._runtimeAnimations;
  51727. if (runtimeAnimations[0]) {
  51728. var fps = runtimeAnimations[0].animation.framePerSecond;
  51729. var currentFrame = runtimeAnimations[0].currentFrame;
  51730. var adjustTime = frame - currentFrame;
  51731. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51732. if (this._localDelayOffset === null) {
  51733. this._localDelayOffset = 0;
  51734. }
  51735. this._localDelayOffset -= delay;
  51736. }
  51737. for (var index = 0; index < runtimeAnimations.length; index++) {
  51738. runtimeAnimations[index].goToFrame(frame);
  51739. }
  51740. };
  51741. /**
  51742. * Pause the animation
  51743. */
  51744. Animatable.prototype.pause = function () {
  51745. if (this._paused) {
  51746. return;
  51747. }
  51748. this._paused = true;
  51749. };
  51750. /**
  51751. * Restart the animation
  51752. */
  51753. Animatable.prototype.restart = function () {
  51754. this._paused = false;
  51755. };
  51756. Animatable.prototype._raiseOnAnimationEnd = function () {
  51757. if (this.onAnimationEnd) {
  51758. this.onAnimationEnd();
  51759. }
  51760. this.onAnimationEndObservable.notifyObservers(this);
  51761. };
  51762. /**
  51763. * Stop and delete the current animation
  51764. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51765. * @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)
  51766. */
  51767. Animatable.prototype.stop = function (animationName, targetMask) {
  51768. if (animationName || targetMask) {
  51769. var idx = this._scene._activeAnimatables.indexOf(this);
  51770. if (idx > -1) {
  51771. var runtimeAnimations = this._runtimeAnimations;
  51772. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51773. var runtimeAnimation = runtimeAnimations[index];
  51774. if (animationName && runtimeAnimation.animation.name != animationName) {
  51775. continue;
  51776. }
  51777. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51778. continue;
  51779. }
  51780. runtimeAnimation.dispose();
  51781. runtimeAnimations.splice(index, 1);
  51782. }
  51783. if (runtimeAnimations.length == 0) {
  51784. this._scene._activeAnimatables.splice(idx, 1);
  51785. this._raiseOnAnimationEnd();
  51786. }
  51787. }
  51788. }
  51789. else {
  51790. var index = this._scene._activeAnimatables.indexOf(this);
  51791. if (index > -1) {
  51792. this._scene._activeAnimatables.splice(index, 1);
  51793. var runtimeAnimations = this._runtimeAnimations;
  51794. for (var index = 0; index < runtimeAnimations.length; index++) {
  51795. runtimeAnimations[index].dispose();
  51796. }
  51797. this._raiseOnAnimationEnd();
  51798. }
  51799. }
  51800. };
  51801. /**
  51802. * Wait asynchronously for the animation to end
  51803. * @returns a promise which will be fullfilled when the animation ends
  51804. */
  51805. Animatable.prototype.waitAsync = function () {
  51806. var _this = this;
  51807. return new Promise(function (resolve, reject) {
  51808. _this.onAnimationEndObservable.add(function () {
  51809. resolve(_this);
  51810. }, undefined, undefined, _this, true);
  51811. });
  51812. };
  51813. /** @hidden */
  51814. Animatable.prototype._animate = function (delay) {
  51815. if (this._paused) {
  51816. this.animationStarted = false;
  51817. if (this._pausedDelay === null) {
  51818. this._pausedDelay = delay;
  51819. }
  51820. return true;
  51821. }
  51822. if (this._localDelayOffset === null) {
  51823. this._localDelayOffset = delay;
  51824. this._pausedDelay = null;
  51825. }
  51826. else if (this._pausedDelay !== null) {
  51827. this._localDelayOffset += delay - this._pausedDelay;
  51828. this._pausedDelay = null;
  51829. }
  51830. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51831. return true;
  51832. }
  51833. // Animating
  51834. var running = false;
  51835. var runtimeAnimations = this._runtimeAnimations;
  51836. var index;
  51837. for (index = 0; index < runtimeAnimations.length; index++) {
  51838. var animation = runtimeAnimations[index];
  51839. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51840. running = running || isRunning;
  51841. }
  51842. this.animationStarted = running;
  51843. if (!running) {
  51844. if (this.disposeOnEnd) {
  51845. // Remove from active animatables
  51846. index = this._scene._activeAnimatables.indexOf(this);
  51847. this._scene._activeAnimatables.splice(index, 1);
  51848. // Dispose all runtime animations
  51849. for (index = 0; index < runtimeAnimations.length; index++) {
  51850. runtimeAnimations[index].dispose();
  51851. }
  51852. }
  51853. this._raiseOnAnimationEnd();
  51854. if (this.disposeOnEnd) {
  51855. this.onAnimationEnd = null;
  51856. this.onAnimationEndObservable.clear();
  51857. }
  51858. }
  51859. return running;
  51860. };
  51861. return Animatable;
  51862. }());
  51863. BABYLON.Animatable = Animatable;
  51864. })(BABYLON || (BABYLON = {}));
  51865. //# sourceMappingURL=babylon.animatable.js.map
  51866. var BABYLON;
  51867. (function (BABYLON) {
  51868. var EasingFunction = /** @class */ (function () {
  51869. function EasingFunction() {
  51870. // Properties
  51871. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51872. }
  51873. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51874. get: function () {
  51875. return EasingFunction._EASINGMODE_EASEIN;
  51876. },
  51877. enumerable: true,
  51878. configurable: true
  51879. });
  51880. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51881. get: function () {
  51882. return EasingFunction._EASINGMODE_EASEOUT;
  51883. },
  51884. enumerable: true,
  51885. configurable: true
  51886. });
  51887. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51888. get: function () {
  51889. return EasingFunction._EASINGMODE_EASEINOUT;
  51890. },
  51891. enumerable: true,
  51892. configurable: true
  51893. });
  51894. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51895. var n = Math.min(Math.max(easingMode, 0), 2);
  51896. this._easingMode = n;
  51897. };
  51898. EasingFunction.prototype.getEasingMode = function () {
  51899. return this._easingMode;
  51900. };
  51901. EasingFunction.prototype.easeInCore = function (gradient) {
  51902. throw new Error('You must implement this method');
  51903. };
  51904. EasingFunction.prototype.ease = function (gradient) {
  51905. switch (this._easingMode) {
  51906. case EasingFunction.EASINGMODE_EASEIN:
  51907. return this.easeInCore(gradient);
  51908. case EasingFunction.EASINGMODE_EASEOUT:
  51909. return (1 - this.easeInCore(1 - gradient));
  51910. }
  51911. if (gradient >= 0.5) {
  51912. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51913. }
  51914. return (this.easeInCore(gradient * 2) * 0.5);
  51915. };
  51916. //Statics
  51917. EasingFunction._EASINGMODE_EASEIN = 0;
  51918. EasingFunction._EASINGMODE_EASEOUT = 1;
  51919. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51920. return EasingFunction;
  51921. }());
  51922. BABYLON.EasingFunction = EasingFunction;
  51923. var CircleEase = /** @class */ (function (_super) {
  51924. __extends(CircleEase, _super);
  51925. function CircleEase() {
  51926. return _super !== null && _super.apply(this, arguments) || this;
  51927. }
  51928. CircleEase.prototype.easeInCore = function (gradient) {
  51929. gradient = Math.max(0, Math.min(1, gradient));
  51930. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51931. };
  51932. return CircleEase;
  51933. }(EasingFunction));
  51934. BABYLON.CircleEase = CircleEase;
  51935. var BackEase = /** @class */ (function (_super) {
  51936. __extends(BackEase, _super);
  51937. function BackEase(amplitude) {
  51938. if (amplitude === void 0) { amplitude = 1; }
  51939. var _this = _super.call(this) || this;
  51940. _this.amplitude = amplitude;
  51941. return _this;
  51942. }
  51943. BackEase.prototype.easeInCore = function (gradient) {
  51944. var num = Math.max(0, this.amplitude);
  51945. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51946. };
  51947. return BackEase;
  51948. }(EasingFunction));
  51949. BABYLON.BackEase = BackEase;
  51950. var BounceEase = /** @class */ (function (_super) {
  51951. __extends(BounceEase, _super);
  51952. function BounceEase(bounces, bounciness) {
  51953. if (bounces === void 0) { bounces = 3; }
  51954. if (bounciness === void 0) { bounciness = 2; }
  51955. var _this = _super.call(this) || this;
  51956. _this.bounces = bounces;
  51957. _this.bounciness = bounciness;
  51958. return _this;
  51959. }
  51960. BounceEase.prototype.easeInCore = function (gradient) {
  51961. var y = Math.max(0.0, this.bounces);
  51962. var bounciness = this.bounciness;
  51963. if (bounciness <= 1.0) {
  51964. bounciness = 1.001;
  51965. }
  51966. var num9 = Math.pow(bounciness, y);
  51967. var num5 = 1.0 - bounciness;
  51968. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51969. var num15 = gradient * num4;
  51970. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51971. var num3 = Math.floor(num65);
  51972. var num13 = num3 + 1.0;
  51973. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51974. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51975. var num7 = (num8 + num12) * 0.5;
  51976. var num6 = gradient - num7;
  51977. var num2 = num7 - num8;
  51978. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51979. };
  51980. return BounceEase;
  51981. }(EasingFunction));
  51982. BABYLON.BounceEase = BounceEase;
  51983. var CubicEase = /** @class */ (function (_super) {
  51984. __extends(CubicEase, _super);
  51985. function CubicEase() {
  51986. return _super !== null && _super.apply(this, arguments) || this;
  51987. }
  51988. CubicEase.prototype.easeInCore = function (gradient) {
  51989. return (gradient * gradient * gradient);
  51990. };
  51991. return CubicEase;
  51992. }(EasingFunction));
  51993. BABYLON.CubicEase = CubicEase;
  51994. var ElasticEase = /** @class */ (function (_super) {
  51995. __extends(ElasticEase, _super);
  51996. function ElasticEase(oscillations, springiness) {
  51997. if (oscillations === void 0) { oscillations = 3; }
  51998. if (springiness === void 0) { springiness = 3; }
  51999. var _this = _super.call(this) || this;
  52000. _this.oscillations = oscillations;
  52001. _this.springiness = springiness;
  52002. return _this;
  52003. }
  52004. ElasticEase.prototype.easeInCore = function (gradient) {
  52005. var num2;
  52006. var num3 = Math.max(0.0, this.oscillations);
  52007. var num = Math.max(0.0, this.springiness);
  52008. if (num == 0) {
  52009. num2 = gradient;
  52010. }
  52011. else {
  52012. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52013. }
  52014. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52015. };
  52016. return ElasticEase;
  52017. }(EasingFunction));
  52018. BABYLON.ElasticEase = ElasticEase;
  52019. var ExponentialEase = /** @class */ (function (_super) {
  52020. __extends(ExponentialEase, _super);
  52021. function ExponentialEase(exponent) {
  52022. if (exponent === void 0) { exponent = 2; }
  52023. var _this = _super.call(this) || this;
  52024. _this.exponent = exponent;
  52025. return _this;
  52026. }
  52027. ExponentialEase.prototype.easeInCore = function (gradient) {
  52028. if (this.exponent <= 0) {
  52029. return gradient;
  52030. }
  52031. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52032. };
  52033. return ExponentialEase;
  52034. }(EasingFunction));
  52035. BABYLON.ExponentialEase = ExponentialEase;
  52036. var PowerEase = /** @class */ (function (_super) {
  52037. __extends(PowerEase, _super);
  52038. function PowerEase(power) {
  52039. if (power === void 0) { power = 2; }
  52040. var _this = _super.call(this) || this;
  52041. _this.power = power;
  52042. return _this;
  52043. }
  52044. PowerEase.prototype.easeInCore = function (gradient) {
  52045. var y = Math.max(0.0, this.power);
  52046. return Math.pow(gradient, y);
  52047. };
  52048. return PowerEase;
  52049. }(EasingFunction));
  52050. BABYLON.PowerEase = PowerEase;
  52051. var QuadraticEase = /** @class */ (function (_super) {
  52052. __extends(QuadraticEase, _super);
  52053. function QuadraticEase() {
  52054. return _super !== null && _super.apply(this, arguments) || this;
  52055. }
  52056. QuadraticEase.prototype.easeInCore = function (gradient) {
  52057. return (gradient * gradient);
  52058. };
  52059. return QuadraticEase;
  52060. }(EasingFunction));
  52061. BABYLON.QuadraticEase = QuadraticEase;
  52062. var QuarticEase = /** @class */ (function (_super) {
  52063. __extends(QuarticEase, _super);
  52064. function QuarticEase() {
  52065. return _super !== null && _super.apply(this, arguments) || this;
  52066. }
  52067. QuarticEase.prototype.easeInCore = function (gradient) {
  52068. return (gradient * gradient * gradient * gradient);
  52069. };
  52070. return QuarticEase;
  52071. }(EasingFunction));
  52072. BABYLON.QuarticEase = QuarticEase;
  52073. var QuinticEase = /** @class */ (function (_super) {
  52074. __extends(QuinticEase, _super);
  52075. function QuinticEase() {
  52076. return _super !== null && _super.apply(this, arguments) || this;
  52077. }
  52078. QuinticEase.prototype.easeInCore = function (gradient) {
  52079. return (gradient * gradient * gradient * gradient * gradient);
  52080. };
  52081. return QuinticEase;
  52082. }(EasingFunction));
  52083. BABYLON.QuinticEase = QuinticEase;
  52084. var SineEase = /** @class */ (function (_super) {
  52085. __extends(SineEase, _super);
  52086. function SineEase() {
  52087. return _super !== null && _super.apply(this, arguments) || this;
  52088. }
  52089. SineEase.prototype.easeInCore = function (gradient) {
  52090. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52091. };
  52092. return SineEase;
  52093. }(EasingFunction));
  52094. BABYLON.SineEase = SineEase;
  52095. var BezierCurveEase = /** @class */ (function (_super) {
  52096. __extends(BezierCurveEase, _super);
  52097. function BezierCurveEase(x1, y1, x2, y2) {
  52098. if (x1 === void 0) { x1 = 0; }
  52099. if (y1 === void 0) { y1 = 0; }
  52100. if (x2 === void 0) { x2 = 1; }
  52101. if (y2 === void 0) { y2 = 1; }
  52102. var _this = _super.call(this) || this;
  52103. _this.x1 = x1;
  52104. _this.y1 = y1;
  52105. _this.x2 = x2;
  52106. _this.y2 = y2;
  52107. return _this;
  52108. }
  52109. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52110. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52111. };
  52112. return BezierCurveEase;
  52113. }(EasingFunction));
  52114. BABYLON.BezierCurveEase = BezierCurveEase;
  52115. })(BABYLON || (BABYLON = {}));
  52116. //# sourceMappingURL=babylon.easing.js.map
  52117. var BABYLON;
  52118. (function (BABYLON) {
  52119. /**
  52120. * A Condition applied to an Action
  52121. */
  52122. var Condition = /** @class */ (function () {
  52123. /**
  52124. * Creates a new Condition
  52125. * @param actionManager the manager of the action the condition is applied to
  52126. */
  52127. function Condition(actionManager) {
  52128. this._actionManager = actionManager;
  52129. }
  52130. /**
  52131. * Check if the current condition is valid
  52132. * @returns a boolean
  52133. */
  52134. Condition.prototype.isValid = function () {
  52135. return true;
  52136. };
  52137. /**
  52138. * Internal only
  52139. * @hidden
  52140. */
  52141. Condition.prototype._getProperty = function (propertyPath) {
  52142. return this._actionManager._getProperty(propertyPath);
  52143. };
  52144. /**
  52145. * Internal only
  52146. * @hidden
  52147. */
  52148. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52149. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52150. };
  52151. /**
  52152. * Serialize placeholder for child classes
  52153. * @returns the serialized object
  52154. */
  52155. Condition.prototype.serialize = function () {
  52156. };
  52157. /**
  52158. * Internal only
  52159. * @hidden
  52160. */
  52161. Condition.prototype._serialize = function (serializedCondition) {
  52162. return {
  52163. type: 2,
  52164. children: [],
  52165. name: serializedCondition.name,
  52166. properties: serializedCondition.properties
  52167. };
  52168. };
  52169. return Condition;
  52170. }());
  52171. BABYLON.Condition = Condition;
  52172. /**
  52173. * Defines specific conditional operators as extensions of Condition
  52174. */
  52175. var ValueCondition = /** @class */ (function (_super) {
  52176. __extends(ValueCondition, _super);
  52177. /**
  52178. * Creates a new ValueCondition
  52179. * @param actionManager manager for the action the condition applies to
  52180. * @param target for the action
  52181. * @param propertyPath path to specify the property of the target the conditional operator uses
  52182. * @param value the value compared by the conditional operator against the current value of the property
  52183. * @param operator the conditional operator, default ValueCondition.IsEqual
  52184. */
  52185. function ValueCondition(actionManager, target,
  52186. /** path to specify the property of the target the conditional operator uses */
  52187. propertyPath,
  52188. /** the value compared by the conditional operator against the current value of the property */
  52189. value,
  52190. /** the conditional operator, default ValueCondition.IsEqual */
  52191. operator) {
  52192. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52193. var _this = _super.call(this, actionManager) || this;
  52194. _this.propertyPath = propertyPath;
  52195. _this.value = value;
  52196. _this.operator = operator;
  52197. _this._target = target;
  52198. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52199. _this._property = _this._getProperty(_this.propertyPath);
  52200. return _this;
  52201. }
  52202. Object.defineProperty(ValueCondition, "IsEqual", {
  52203. /**
  52204. * returns the number for IsEqual
  52205. */
  52206. get: function () {
  52207. return ValueCondition._IsEqual;
  52208. },
  52209. enumerable: true,
  52210. configurable: true
  52211. });
  52212. Object.defineProperty(ValueCondition, "IsDifferent", {
  52213. /**
  52214. * Returns the number for IsDifferent
  52215. */
  52216. get: function () {
  52217. return ValueCondition._IsDifferent;
  52218. },
  52219. enumerable: true,
  52220. configurable: true
  52221. });
  52222. Object.defineProperty(ValueCondition, "IsGreater", {
  52223. /**
  52224. * Returns the number for IsGreater
  52225. */
  52226. get: function () {
  52227. return ValueCondition._IsGreater;
  52228. },
  52229. enumerable: true,
  52230. configurable: true
  52231. });
  52232. Object.defineProperty(ValueCondition, "IsLesser", {
  52233. /**
  52234. * Returns the number for IsLesser
  52235. */
  52236. get: function () {
  52237. return ValueCondition._IsLesser;
  52238. },
  52239. enumerable: true,
  52240. configurable: true
  52241. });
  52242. /**
  52243. * Compares the given value with the property value for the specified conditional operator
  52244. * @returns the result of the comparison
  52245. */
  52246. ValueCondition.prototype.isValid = function () {
  52247. switch (this.operator) {
  52248. case ValueCondition.IsGreater:
  52249. return this._effectiveTarget[this._property] > this.value;
  52250. case ValueCondition.IsLesser:
  52251. return this._effectiveTarget[this._property] < this.value;
  52252. case ValueCondition.IsEqual:
  52253. case ValueCondition.IsDifferent:
  52254. var check;
  52255. if (this.value.equals) {
  52256. check = this.value.equals(this._effectiveTarget[this._property]);
  52257. }
  52258. else {
  52259. check = this.value === this._effectiveTarget[this._property];
  52260. }
  52261. return this.operator === ValueCondition.IsEqual ? check : !check;
  52262. }
  52263. return false;
  52264. };
  52265. /**
  52266. * Serialize the ValueCondition into a JSON compatible object
  52267. * @returns serialization object
  52268. */
  52269. ValueCondition.prototype.serialize = function () {
  52270. return this._serialize({
  52271. name: "ValueCondition",
  52272. properties: [
  52273. BABYLON.Action._GetTargetProperty(this._target),
  52274. { name: "propertyPath", value: this.propertyPath },
  52275. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52276. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52277. ]
  52278. });
  52279. };
  52280. /**
  52281. * Gets the name of the conditional operator for the ValueCondition
  52282. * @param operator the conditional operator
  52283. * @returns the name
  52284. */
  52285. ValueCondition.GetOperatorName = function (operator) {
  52286. switch (operator) {
  52287. case ValueCondition._IsEqual: return "IsEqual";
  52288. case ValueCondition._IsDifferent: return "IsDifferent";
  52289. case ValueCondition._IsGreater: return "IsGreater";
  52290. case ValueCondition._IsLesser: return "IsLesser";
  52291. default: return "";
  52292. }
  52293. };
  52294. /**
  52295. * Internal only
  52296. * @hidden
  52297. */
  52298. ValueCondition._IsEqual = 0;
  52299. /**
  52300. * Internal only
  52301. * @hidden
  52302. */
  52303. ValueCondition._IsDifferent = 1;
  52304. /**
  52305. * Internal only
  52306. * @hidden
  52307. */
  52308. ValueCondition._IsGreater = 2;
  52309. /**
  52310. * Internal only
  52311. * @hidden
  52312. */
  52313. ValueCondition._IsLesser = 3;
  52314. return ValueCondition;
  52315. }(Condition));
  52316. BABYLON.ValueCondition = ValueCondition;
  52317. /**
  52318. * Defines a predicate condition as an extension of Condition
  52319. */
  52320. var PredicateCondition = /** @class */ (function (_super) {
  52321. __extends(PredicateCondition, _super);
  52322. /**
  52323. * Creates a new PredicateCondition
  52324. * @param actionManager manager for the action the condition applies to
  52325. * @param predicate defines the predicate function used to validate the condition
  52326. */
  52327. function PredicateCondition(actionManager,
  52328. /** defines the predicate function used to validate the condition */
  52329. predicate) {
  52330. var _this = _super.call(this, actionManager) || this;
  52331. _this.predicate = predicate;
  52332. return _this;
  52333. }
  52334. /**
  52335. * @returns the validity of the predicate condition
  52336. */
  52337. PredicateCondition.prototype.isValid = function () {
  52338. return this.predicate();
  52339. };
  52340. return PredicateCondition;
  52341. }(Condition));
  52342. BABYLON.PredicateCondition = PredicateCondition;
  52343. /**
  52344. * Defines a state condition as an extension of Condition
  52345. */
  52346. var StateCondition = /** @class */ (function (_super) {
  52347. __extends(StateCondition, _super);
  52348. /**
  52349. * Creates a new StateCondition
  52350. * @param actionManager manager for the action the condition applies to
  52351. * @param target of the condition
  52352. * @param value to compare with target state
  52353. */
  52354. function StateCondition(actionManager, target, value) {
  52355. var _this = _super.call(this, actionManager) || this;
  52356. _this.value = value;
  52357. _this._target = target;
  52358. return _this;
  52359. }
  52360. /**
  52361. * @returns the validity of the state
  52362. */
  52363. StateCondition.prototype.isValid = function () {
  52364. return this._target.state === this.value;
  52365. };
  52366. /**
  52367. * Serialize the StateCondition into a JSON compatible object
  52368. * @returns serialization object
  52369. */
  52370. StateCondition.prototype.serialize = function () {
  52371. return this._serialize({
  52372. name: "StateCondition",
  52373. properties: [
  52374. BABYLON.Action._GetTargetProperty(this._target),
  52375. { name: "value", value: this.value }
  52376. ]
  52377. });
  52378. };
  52379. return StateCondition;
  52380. }(Condition));
  52381. BABYLON.StateCondition = StateCondition;
  52382. })(BABYLON || (BABYLON = {}));
  52383. //# sourceMappingURL=babylon.condition.js.map
  52384. var BABYLON;
  52385. (function (BABYLON) {
  52386. /**
  52387. * The action to be carried out following a trigger
  52388. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52389. */
  52390. var Action = /** @class */ (function () {
  52391. /**
  52392. * Creates a new Action
  52393. * @param triggerOptions the trigger, with or without parameters, for the action
  52394. * @param condition an optional determinant of action
  52395. */
  52396. function Action(
  52397. /** the trigger, with or without parameters, for the action */
  52398. triggerOptions, condition) {
  52399. this.triggerOptions = triggerOptions;
  52400. /**
  52401. * An event triggered prior to action being executed.
  52402. */
  52403. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52404. if (triggerOptions.parameter) {
  52405. this.trigger = triggerOptions.trigger;
  52406. this._triggerParameter = triggerOptions.parameter;
  52407. }
  52408. else {
  52409. this.trigger = triggerOptions;
  52410. }
  52411. this._nextActiveAction = this;
  52412. this._condition = condition;
  52413. }
  52414. /**
  52415. * Internal only
  52416. * @hidden
  52417. */
  52418. Action.prototype._prepare = function () {
  52419. };
  52420. /**
  52421. * Gets the trigger parameters
  52422. * @returns the trigger parameters
  52423. */
  52424. Action.prototype.getTriggerParameter = function () {
  52425. return this._triggerParameter;
  52426. };
  52427. /**
  52428. * Internal only - executes current action event
  52429. * @hidden
  52430. */
  52431. Action.prototype._executeCurrent = function (evt) {
  52432. if (this._nextActiveAction._condition) {
  52433. var condition = this._nextActiveAction._condition;
  52434. var currentRenderId = this._actionManager.getScene().getRenderId();
  52435. // We cache the current evaluation for the current frame
  52436. if (condition._evaluationId === currentRenderId) {
  52437. if (!condition._currentResult) {
  52438. return;
  52439. }
  52440. }
  52441. else {
  52442. condition._evaluationId = currentRenderId;
  52443. if (!condition.isValid()) {
  52444. condition._currentResult = false;
  52445. return;
  52446. }
  52447. condition._currentResult = true;
  52448. }
  52449. }
  52450. this.onBeforeExecuteObservable.notifyObservers(this);
  52451. this._nextActiveAction.execute(evt);
  52452. this.skipToNextActiveAction();
  52453. };
  52454. /**
  52455. * Execute placeholder for child classes
  52456. * @param evt optional action event
  52457. */
  52458. Action.prototype.execute = function (evt) {
  52459. };
  52460. /**
  52461. * Skips to next active action
  52462. */
  52463. Action.prototype.skipToNextActiveAction = function () {
  52464. if (this._nextActiveAction._child) {
  52465. if (!this._nextActiveAction._child._actionManager) {
  52466. this._nextActiveAction._child._actionManager = this._actionManager;
  52467. }
  52468. this._nextActiveAction = this._nextActiveAction._child;
  52469. }
  52470. else {
  52471. this._nextActiveAction = this;
  52472. }
  52473. };
  52474. /**
  52475. * Adds action to chain of actions, may be a DoNothingAction
  52476. * @param action defines the next action to execute
  52477. * @returns The action passed in
  52478. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52479. */
  52480. Action.prototype.then = function (action) {
  52481. this._child = action;
  52482. action._actionManager = this._actionManager;
  52483. action._prepare();
  52484. return action;
  52485. };
  52486. /**
  52487. * Internal only
  52488. * @hidden
  52489. */
  52490. Action.prototype._getProperty = function (propertyPath) {
  52491. return this._actionManager._getProperty(propertyPath);
  52492. };
  52493. /**
  52494. * Internal only
  52495. * @hidden
  52496. */
  52497. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52498. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52499. };
  52500. /**
  52501. * Serialize placeholder for child classes
  52502. * @param parent of child
  52503. * @returns the serialized object
  52504. */
  52505. Action.prototype.serialize = function (parent) {
  52506. };
  52507. /**
  52508. * Internal only called by serialize
  52509. * @hidden
  52510. */
  52511. Action.prototype._serialize = function (serializedAction, parent) {
  52512. var serializationObject = {
  52513. type: 1,
  52514. children: [],
  52515. name: serializedAction.name,
  52516. properties: serializedAction.properties || []
  52517. };
  52518. // Serialize child
  52519. if (this._child) {
  52520. this._child.serialize(serializationObject);
  52521. }
  52522. // Check if "this" has a condition
  52523. if (this._condition) {
  52524. var serializedCondition = this._condition.serialize();
  52525. serializedCondition.children.push(serializationObject);
  52526. if (parent) {
  52527. parent.children.push(serializedCondition);
  52528. }
  52529. return serializedCondition;
  52530. }
  52531. if (parent) {
  52532. parent.children.push(serializationObject);
  52533. }
  52534. return serializationObject;
  52535. };
  52536. /**
  52537. * Internal only
  52538. * @hidden
  52539. */
  52540. Action._SerializeValueAsString = function (value) {
  52541. if (typeof value === "number") {
  52542. return value.toString();
  52543. }
  52544. if (typeof value === "boolean") {
  52545. return value ? "true" : "false";
  52546. }
  52547. if (value instanceof BABYLON.Vector2) {
  52548. return value.x + ", " + value.y;
  52549. }
  52550. if (value instanceof BABYLON.Vector3) {
  52551. return value.x + ", " + value.y + ", " + value.z;
  52552. }
  52553. if (value instanceof BABYLON.Color3) {
  52554. return value.r + ", " + value.g + ", " + value.b;
  52555. }
  52556. if (value instanceof BABYLON.Color4) {
  52557. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52558. }
  52559. return value; // string
  52560. };
  52561. /**
  52562. * Internal only
  52563. * @hidden
  52564. */
  52565. Action._GetTargetProperty = function (target) {
  52566. return {
  52567. name: "target",
  52568. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52569. : target instanceof BABYLON.Light ? "LightProperties"
  52570. : target instanceof BABYLON.Camera ? "CameraProperties"
  52571. : "SceneProperties",
  52572. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52573. };
  52574. };
  52575. return Action;
  52576. }());
  52577. BABYLON.Action = Action;
  52578. })(BABYLON || (BABYLON = {}));
  52579. //# sourceMappingURL=babylon.action.js.map
  52580. var BABYLON;
  52581. (function (BABYLON) {
  52582. /**
  52583. * ActionEvent is the event being sent when an action is triggered.
  52584. */
  52585. var ActionEvent = /** @class */ (function () {
  52586. /**
  52587. * Creates a new ActionEvent
  52588. * @param source The mesh or sprite that triggered the action
  52589. * @param pointerX The X mouse cursor position at the time of the event
  52590. * @param pointerY The Y mouse cursor position at the time of the event
  52591. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52592. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52593. * @param additionalData additional data for the event
  52594. */
  52595. function ActionEvent(
  52596. /** The mesh or sprite that triggered the action */
  52597. source,
  52598. /** The X mouse cursor position at the time of the event */
  52599. pointerX,
  52600. /** The Y mouse cursor position at the time of the event */
  52601. pointerY,
  52602. /** The mesh that is currently pointed at (can be null) */
  52603. meshUnderPointer,
  52604. /** the original (browser) event that triggered the ActionEvent */
  52605. sourceEvent,
  52606. /** additional data for the event */
  52607. additionalData) {
  52608. this.source = source;
  52609. this.pointerX = pointerX;
  52610. this.pointerY = pointerY;
  52611. this.meshUnderPointer = meshUnderPointer;
  52612. this.sourceEvent = sourceEvent;
  52613. this.additionalData = additionalData;
  52614. }
  52615. /**
  52616. * Helper function to auto-create an ActionEvent from a source mesh.
  52617. * @param source The source mesh that triggered the event
  52618. * @param evt The original (browser) event
  52619. * @param additionalData additional data for the event
  52620. * @returns the new ActionEvent
  52621. */
  52622. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52623. var scene = source.getScene();
  52624. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52625. };
  52626. /**
  52627. * Helper function to auto-create an ActionEvent from a source sprite
  52628. * @param source The source sprite that triggered the event
  52629. * @param scene Scene associated with the sprite
  52630. * @param evt The original (browser) event
  52631. * @param additionalData additional data for the event
  52632. * @returns the new ActionEvent
  52633. */
  52634. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52635. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52636. };
  52637. /**
  52638. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52639. * @param scene the scene where the event occurred
  52640. * @param evt The original (browser) event
  52641. * @returns the new ActionEvent
  52642. */
  52643. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52644. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52645. };
  52646. /**
  52647. * Helper function to auto-create an ActionEvent from a primitive
  52648. * @param prim defines the target primitive
  52649. * @param pointerPos defines the pointer position
  52650. * @param evt The original (browser) event
  52651. * @param additionalData additional data for the event
  52652. * @returns the new ActionEvent
  52653. */
  52654. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52655. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52656. };
  52657. return ActionEvent;
  52658. }());
  52659. BABYLON.ActionEvent = ActionEvent;
  52660. /**
  52661. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52662. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52663. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52664. */
  52665. var ActionManager = /** @class */ (function () {
  52666. /**
  52667. * Creates a new action manager
  52668. * @param scene defines the hosting scene
  52669. */
  52670. function ActionManager(scene) {
  52671. // Members
  52672. /** Gets the list of actions */
  52673. this.actions = new Array();
  52674. /** Gets the cursor to use when hovering items */
  52675. this.hoverCursor = '';
  52676. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52677. scene.actionManagers.push(this);
  52678. }
  52679. Object.defineProperty(ActionManager, "NothingTrigger", {
  52680. /**
  52681. * Nothing
  52682. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52683. */
  52684. get: function () {
  52685. return ActionManager._NothingTrigger;
  52686. },
  52687. enumerable: true,
  52688. configurable: true
  52689. });
  52690. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52691. /**
  52692. * On pick
  52693. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52694. */
  52695. get: function () {
  52696. return ActionManager._OnPickTrigger;
  52697. },
  52698. enumerable: true,
  52699. configurable: true
  52700. });
  52701. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52702. /**
  52703. * On left pick
  52704. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52705. */
  52706. get: function () {
  52707. return ActionManager._OnLeftPickTrigger;
  52708. },
  52709. enumerable: true,
  52710. configurable: true
  52711. });
  52712. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52713. /**
  52714. * On right pick
  52715. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52716. */
  52717. get: function () {
  52718. return ActionManager._OnRightPickTrigger;
  52719. },
  52720. enumerable: true,
  52721. configurable: true
  52722. });
  52723. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52724. /**
  52725. * On center pick
  52726. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52727. */
  52728. get: function () {
  52729. return ActionManager._OnCenterPickTrigger;
  52730. },
  52731. enumerable: true,
  52732. configurable: true
  52733. });
  52734. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52735. /**
  52736. * On pick down
  52737. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52738. */
  52739. get: function () {
  52740. return ActionManager._OnPickDownTrigger;
  52741. },
  52742. enumerable: true,
  52743. configurable: true
  52744. });
  52745. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52746. /**
  52747. * On double pick
  52748. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52749. */
  52750. get: function () {
  52751. return ActionManager._OnDoublePickTrigger;
  52752. },
  52753. enumerable: true,
  52754. configurable: true
  52755. });
  52756. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52757. /**
  52758. * On pick up
  52759. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52760. */
  52761. get: function () {
  52762. return ActionManager._OnPickUpTrigger;
  52763. },
  52764. enumerable: true,
  52765. configurable: true
  52766. });
  52767. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52768. /**
  52769. * On pick out.
  52770. * This trigger will only be raised if you also declared a OnPickDown
  52771. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52772. */
  52773. get: function () {
  52774. return ActionManager._OnPickOutTrigger;
  52775. },
  52776. enumerable: true,
  52777. configurable: true
  52778. });
  52779. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52780. /**
  52781. * On long press
  52782. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52783. */
  52784. get: function () {
  52785. return ActionManager._OnLongPressTrigger;
  52786. },
  52787. enumerable: true,
  52788. configurable: true
  52789. });
  52790. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52791. /**
  52792. * On pointer over
  52793. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52794. */
  52795. get: function () {
  52796. return ActionManager._OnPointerOverTrigger;
  52797. },
  52798. enumerable: true,
  52799. configurable: true
  52800. });
  52801. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52802. /**
  52803. * On pointer out
  52804. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52805. */
  52806. get: function () {
  52807. return ActionManager._OnPointerOutTrigger;
  52808. },
  52809. enumerable: true,
  52810. configurable: true
  52811. });
  52812. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52813. /**
  52814. * On every frame
  52815. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52816. */
  52817. get: function () {
  52818. return ActionManager._OnEveryFrameTrigger;
  52819. },
  52820. enumerable: true,
  52821. configurable: true
  52822. });
  52823. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52824. /**
  52825. * On intersection enter
  52826. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52827. */
  52828. get: function () {
  52829. return ActionManager._OnIntersectionEnterTrigger;
  52830. },
  52831. enumerable: true,
  52832. configurable: true
  52833. });
  52834. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52835. /**
  52836. * On intersection exit
  52837. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52838. */
  52839. get: function () {
  52840. return ActionManager._OnIntersectionExitTrigger;
  52841. },
  52842. enumerable: true,
  52843. configurable: true
  52844. });
  52845. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52846. /**
  52847. * On key down
  52848. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52849. */
  52850. get: function () {
  52851. return ActionManager._OnKeyDownTrigger;
  52852. },
  52853. enumerable: true,
  52854. configurable: true
  52855. });
  52856. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52857. /**
  52858. * On key up
  52859. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52860. */
  52861. get: function () {
  52862. return ActionManager._OnKeyUpTrigger;
  52863. },
  52864. enumerable: true,
  52865. configurable: true
  52866. });
  52867. // Methods
  52868. /**
  52869. * Releases all associated resources
  52870. */
  52871. ActionManager.prototype.dispose = function () {
  52872. var index = this._scene.actionManagers.indexOf(this);
  52873. for (var i = 0; i < this.actions.length; i++) {
  52874. var action = this.actions[i];
  52875. ActionManager.Triggers[action.trigger]--;
  52876. if (ActionManager.Triggers[action.trigger] === 0) {
  52877. delete ActionManager.Triggers[action.trigger];
  52878. }
  52879. }
  52880. if (index > -1) {
  52881. this._scene.actionManagers.splice(index, 1);
  52882. }
  52883. };
  52884. /**
  52885. * Gets hosting scene
  52886. * @returns the hosting scene
  52887. */
  52888. ActionManager.prototype.getScene = function () {
  52889. return this._scene;
  52890. };
  52891. /**
  52892. * Does this action manager handles actions of any of the given triggers
  52893. * @param triggers defines the triggers to be tested
  52894. * @return a boolean indicating whether one (or more) of the triggers is handled
  52895. */
  52896. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52897. for (var index = 0; index < this.actions.length; index++) {
  52898. var action = this.actions[index];
  52899. if (triggers.indexOf(action.trigger) > -1) {
  52900. return true;
  52901. }
  52902. }
  52903. return false;
  52904. };
  52905. /**
  52906. * Does this action manager handles actions of a given trigger
  52907. * @param trigger defines the trigger to be tested
  52908. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52909. * @return whether the trigger is handled
  52910. */
  52911. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52912. for (var index = 0; index < this.actions.length; index++) {
  52913. var action = this.actions[index];
  52914. if (action.trigger === trigger) {
  52915. if (parameterPredicate) {
  52916. if (parameterPredicate(action.getTriggerParameter())) {
  52917. return true;
  52918. }
  52919. }
  52920. else {
  52921. return true;
  52922. }
  52923. }
  52924. }
  52925. return false;
  52926. };
  52927. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52928. /**
  52929. * Does this action manager has pointer triggers
  52930. */
  52931. get: function () {
  52932. for (var index = 0; index < this.actions.length; index++) {
  52933. var action = this.actions[index];
  52934. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52935. return true;
  52936. }
  52937. }
  52938. return false;
  52939. },
  52940. enumerable: true,
  52941. configurable: true
  52942. });
  52943. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52944. /**
  52945. * Does this action manager has pick triggers
  52946. */
  52947. get: function () {
  52948. for (var index = 0; index < this.actions.length; index++) {
  52949. var action = this.actions[index];
  52950. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52951. return true;
  52952. }
  52953. }
  52954. return false;
  52955. },
  52956. enumerable: true,
  52957. configurable: true
  52958. });
  52959. Object.defineProperty(ActionManager, "HasTriggers", {
  52960. /**
  52961. * Does exist one action manager with at least one trigger
  52962. **/
  52963. get: function () {
  52964. for (var t in ActionManager.Triggers) {
  52965. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52966. return true;
  52967. }
  52968. }
  52969. return false;
  52970. },
  52971. enumerable: true,
  52972. configurable: true
  52973. });
  52974. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52975. /**
  52976. * Does exist one action manager with at least one pick trigger
  52977. **/
  52978. get: function () {
  52979. for (var t in ActionManager.Triggers) {
  52980. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52981. var t_int = parseInt(t);
  52982. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52983. return true;
  52984. }
  52985. }
  52986. }
  52987. return false;
  52988. },
  52989. enumerable: true,
  52990. configurable: true
  52991. });
  52992. /**
  52993. * Does exist one action manager that handles actions of a given trigger
  52994. * @param trigger defines the trigger to be tested
  52995. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52996. **/
  52997. ActionManager.HasSpecificTrigger = function (trigger) {
  52998. for (var t in ActionManager.Triggers) {
  52999. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53000. var t_int = parseInt(t);
  53001. if (t_int === trigger) {
  53002. return true;
  53003. }
  53004. }
  53005. }
  53006. return false;
  53007. };
  53008. /**
  53009. * Registers an action to this action manager
  53010. * @param action defines the action to be registered
  53011. * @return the action amended (prepared) after registration
  53012. */
  53013. ActionManager.prototype.registerAction = function (action) {
  53014. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53015. if (this.getScene().actionManager !== this) {
  53016. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53017. return null;
  53018. }
  53019. }
  53020. this.actions.push(action);
  53021. if (ActionManager.Triggers[action.trigger]) {
  53022. ActionManager.Triggers[action.trigger]++;
  53023. }
  53024. else {
  53025. ActionManager.Triggers[action.trigger] = 1;
  53026. }
  53027. action._actionManager = this;
  53028. action._prepare();
  53029. return action;
  53030. };
  53031. /**
  53032. * Unregisters an action to this action manager
  53033. * @param action defines the action to be unregistered
  53034. * @return a boolean indicating whether the action has been unregistered
  53035. */
  53036. ActionManager.prototype.unregisterAction = function (action) {
  53037. var index = this.actions.indexOf(action);
  53038. if (index !== -1) {
  53039. this.actions.splice(index, 1);
  53040. ActionManager.Triggers[action.trigger] -= 1;
  53041. if (ActionManager.Triggers[action.trigger] === 0) {
  53042. delete ActionManager.Triggers[action.trigger];
  53043. }
  53044. delete action._actionManager;
  53045. return true;
  53046. }
  53047. return false;
  53048. };
  53049. /**
  53050. * Process a specific trigger
  53051. * @param trigger defines the trigger to process
  53052. * @param evt defines the event details to be processed
  53053. */
  53054. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53055. for (var index = 0; index < this.actions.length; index++) {
  53056. var action = this.actions[index];
  53057. if (action.trigger === trigger) {
  53058. if (evt) {
  53059. if (trigger === ActionManager.OnKeyUpTrigger
  53060. || trigger === ActionManager.OnKeyDownTrigger) {
  53061. var parameter = action.getTriggerParameter();
  53062. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53063. if (!parameter.toLowerCase) {
  53064. continue;
  53065. }
  53066. var lowerCase = parameter.toLowerCase();
  53067. if (lowerCase !== evt.sourceEvent.key) {
  53068. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53069. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53070. if (actualkey !== lowerCase) {
  53071. continue;
  53072. }
  53073. }
  53074. }
  53075. }
  53076. }
  53077. action._executeCurrent(evt);
  53078. }
  53079. }
  53080. };
  53081. /** @hidden */
  53082. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53083. var properties = propertyPath.split(".");
  53084. for (var index = 0; index < properties.length - 1; index++) {
  53085. target = target[properties[index]];
  53086. }
  53087. return target;
  53088. };
  53089. /** @hidden */
  53090. ActionManager.prototype._getProperty = function (propertyPath) {
  53091. var properties = propertyPath.split(".");
  53092. return properties[properties.length - 1];
  53093. };
  53094. /**
  53095. * Serialize this manager to a JSON object
  53096. * @param name defines the property name to store this manager
  53097. * @returns a JSON representation of this manager
  53098. */
  53099. ActionManager.prototype.serialize = function (name) {
  53100. var root = {
  53101. children: new Array(),
  53102. name: name,
  53103. type: 3,
  53104. properties: new Array() // Empty for root but required
  53105. };
  53106. for (var i = 0; i < this.actions.length; i++) {
  53107. var triggerObject = {
  53108. type: 0,
  53109. children: new Array(),
  53110. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53111. properties: new Array()
  53112. };
  53113. var triggerOptions = this.actions[i].triggerOptions;
  53114. if (triggerOptions && typeof triggerOptions !== "number") {
  53115. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53116. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53117. }
  53118. else {
  53119. var parameter = {};
  53120. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53121. if (triggerOptions.parameter.mesh) {
  53122. parameter._meshId = triggerOptions.parameter.mesh.id;
  53123. }
  53124. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53125. }
  53126. }
  53127. // Serialize child action, recursively
  53128. this.actions[i].serialize(triggerObject);
  53129. // Add serialized trigger
  53130. root.children.push(triggerObject);
  53131. }
  53132. return root;
  53133. };
  53134. /**
  53135. * Creates a new ActionManager from a JSON data
  53136. * @param parsedActions defines the JSON data to read from
  53137. * @param object defines the hosting mesh
  53138. * @param scene defines the hosting scene
  53139. */
  53140. ActionManager.Parse = function (parsedActions, object, scene) {
  53141. var actionManager = new ActionManager(scene);
  53142. if (object === null)
  53143. scene.actionManager = actionManager;
  53144. else
  53145. object.actionManager = actionManager;
  53146. // instanciate a new object
  53147. var instanciate = function (name, params) {
  53148. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53149. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53150. newInstance.constructor.apply(newInstance, params);
  53151. return newInstance;
  53152. };
  53153. var parseParameter = function (name, value, target, propertyPath) {
  53154. if (propertyPath === null) {
  53155. // String, boolean or float
  53156. var floatValue = parseFloat(value);
  53157. if (value === "true" || value === "false")
  53158. return value === "true";
  53159. else
  53160. return isNaN(floatValue) ? value : floatValue;
  53161. }
  53162. var effectiveTarget = propertyPath.split(".");
  53163. var values = value.split(",");
  53164. // Get effective Target
  53165. for (var i = 0; i < effectiveTarget.length; i++) {
  53166. target = target[effectiveTarget[i]];
  53167. }
  53168. // Return appropriate value with its type
  53169. if (typeof (target) === "boolean")
  53170. return values[0] === "true";
  53171. if (typeof (target) === "string")
  53172. return values[0];
  53173. // Parameters with multiple values such as Vector3 etc.
  53174. var split = new Array();
  53175. for (var i = 0; i < values.length; i++)
  53176. split.push(parseFloat(values[i]));
  53177. if (target instanceof BABYLON.Vector3)
  53178. return BABYLON.Vector3.FromArray(split);
  53179. if (target instanceof BABYLON.Vector4)
  53180. return BABYLON.Vector4.FromArray(split);
  53181. if (target instanceof BABYLON.Color3)
  53182. return BABYLON.Color3.FromArray(split);
  53183. if (target instanceof BABYLON.Color4)
  53184. return BABYLON.Color4.FromArray(split);
  53185. return parseFloat(values[0]);
  53186. };
  53187. // traverse graph per trigger
  53188. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53189. if (combineArray === void 0) { combineArray = null; }
  53190. if (parsedAction.detached)
  53191. return;
  53192. var parameters = new Array();
  53193. var target = null;
  53194. var propertyPath = null;
  53195. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53196. // Parameters
  53197. if (parsedAction.type === 2)
  53198. parameters.push(actionManager);
  53199. else
  53200. parameters.push(trigger);
  53201. if (combine) {
  53202. var actions = new Array();
  53203. for (var j = 0; j < parsedAction.combine.length; j++) {
  53204. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53205. }
  53206. parameters.push(actions);
  53207. }
  53208. else {
  53209. for (var i = 0; i < parsedAction.properties.length; i++) {
  53210. var value = parsedAction.properties[i].value;
  53211. var name = parsedAction.properties[i].name;
  53212. var targetType = parsedAction.properties[i].targetType;
  53213. if (name === "target")
  53214. if (targetType !== null && targetType === "SceneProperties")
  53215. value = target = scene;
  53216. else
  53217. value = target = scene.getNodeByName(value);
  53218. else if (name === "parent")
  53219. value = scene.getNodeByName(value);
  53220. else if (name === "sound")
  53221. value = scene.getSoundByName(value);
  53222. else if (name !== "propertyPath") {
  53223. if (parsedAction.type === 2 && name === "operator")
  53224. value = BABYLON.ValueCondition[value];
  53225. else
  53226. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53227. }
  53228. else {
  53229. propertyPath = value;
  53230. }
  53231. parameters.push(value);
  53232. }
  53233. }
  53234. if (combineArray === null) {
  53235. parameters.push(condition);
  53236. }
  53237. else {
  53238. parameters.push(null);
  53239. }
  53240. // If interpolate value action
  53241. if (parsedAction.name === "InterpolateValueAction") {
  53242. var param = parameters[parameters.length - 2];
  53243. parameters[parameters.length - 1] = param;
  53244. parameters[parameters.length - 2] = condition;
  53245. }
  53246. // Action or condition(s) and not CombineAction
  53247. var newAction = instanciate(parsedAction.name, parameters);
  53248. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53249. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53250. if (action)
  53251. action.then(nothing);
  53252. else
  53253. actionManager.registerAction(nothing);
  53254. action = nothing;
  53255. }
  53256. if (combineArray === null) {
  53257. if (newAction instanceof BABYLON.Condition) {
  53258. condition = newAction;
  53259. newAction = action;
  53260. }
  53261. else {
  53262. condition = null;
  53263. if (action)
  53264. action.then(newAction);
  53265. else
  53266. actionManager.registerAction(newAction);
  53267. }
  53268. }
  53269. else {
  53270. combineArray.push(newAction);
  53271. }
  53272. for (var i = 0; i < parsedAction.children.length; i++)
  53273. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53274. };
  53275. // triggers
  53276. for (var i = 0; i < parsedActions.children.length; i++) {
  53277. var triggerParams;
  53278. var trigger = parsedActions.children[i];
  53279. if (trigger.properties.length > 0) {
  53280. var param = trigger.properties[0].value;
  53281. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53282. if (value._meshId) {
  53283. value.mesh = scene.getMeshByID(value._meshId);
  53284. }
  53285. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53286. }
  53287. else
  53288. triggerParams = ActionManager[trigger.name];
  53289. for (var j = 0; j < trigger.children.length; j++) {
  53290. if (!trigger.detached)
  53291. traverse(trigger.children[j], triggerParams, null, null);
  53292. }
  53293. }
  53294. };
  53295. /**
  53296. * Get a trigger name by index
  53297. * @param trigger defines the trigger index
  53298. * @returns a trigger name
  53299. */
  53300. ActionManager.GetTriggerName = function (trigger) {
  53301. switch (trigger) {
  53302. case 0: return "NothingTrigger";
  53303. case 1: return "OnPickTrigger";
  53304. case 2: return "OnLeftPickTrigger";
  53305. case 3: return "OnRightPickTrigger";
  53306. case 4: return "OnCenterPickTrigger";
  53307. case 5: return "OnPickDownTrigger";
  53308. case 6: return "OnPickUpTrigger";
  53309. case 7: return "OnLongPressTrigger";
  53310. case 8: return "OnPointerOverTrigger";
  53311. case 9: return "OnPointerOutTrigger";
  53312. case 10: return "OnEveryFrameTrigger";
  53313. case 11: return "OnIntersectionEnterTrigger";
  53314. case 12: return "OnIntersectionExitTrigger";
  53315. case 13: return "OnKeyDownTrigger";
  53316. case 14: return "OnKeyUpTrigger";
  53317. case 15: return "OnPickOutTrigger";
  53318. default: return "";
  53319. }
  53320. };
  53321. // Statics
  53322. ActionManager._NothingTrigger = 0;
  53323. ActionManager._OnPickTrigger = 1;
  53324. ActionManager._OnLeftPickTrigger = 2;
  53325. ActionManager._OnRightPickTrigger = 3;
  53326. ActionManager._OnCenterPickTrigger = 4;
  53327. ActionManager._OnPickDownTrigger = 5;
  53328. ActionManager._OnDoublePickTrigger = 6;
  53329. ActionManager._OnPickUpTrigger = 7;
  53330. ActionManager._OnLongPressTrigger = 8;
  53331. ActionManager._OnPointerOverTrigger = 9;
  53332. ActionManager._OnPointerOutTrigger = 10;
  53333. ActionManager._OnEveryFrameTrigger = 11;
  53334. ActionManager._OnIntersectionEnterTrigger = 12;
  53335. ActionManager._OnIntersectionExitTrigger = 13;
  53336. ActionManager._OnKeyDownTrigger = 14;
  53337. ActionManager._OnKeyUpTrigger = 15;
  53338. ActionManager._OnPickOutTrigger = 16;
  53339. /** Gets the list of active triggers */
  53340. ActionManager.Triggers = {};
  53341. return ActionManager;
  53342. }());
  53343. BABYLON.ActionManager = ActionManager;
  53344. })(BABYLON || (BABYLON = {}));
  53345. //# sourceMappingURL=babylon.actionManager.js.map
  53346. var BABYLON;
  53347. (function (BABYLON) {
  53348. var InterpolateValueAction = /** @class */ (function (_super) {
  53349. __extends(InterpolateValueAction, _super);
  53350. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53351. if (duration === void 0) { duration = 1000; }
  53352. var _this = _super.call(this, triggerOptions, condition) || this;
  53353. _this.propertyPath = propertyPath;
  53354. _this.value = value;
  53355. _this.duration = duration;
  53356. _this.stopOtherAnimations = stopOtherAnimations;
  53357. _this.onInterpolationDone = onInterpolationDone;
  53358. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53359. _this._target = _this._effectiveTarget = target;
  53360. return _this;
  53361. }
  53362. /** @hidden */
  53363. InterpolateValueAction.prototype._prepare = function () {
  53364. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53365. this._property = this._getProperty(this.propertyPath);
  53366. };
  53367. InterpolateValueAction.prototype.execute = function () {
  53368. var _this = this;
  53369. var scene = this._actionManager.getScene();
  53370. var keys = [
  53371. {
  53372. frame: 0,
  53373. value: this._effectiveTarget[this._property]
  53374. }, {
  53375. frame: 100,
  53376. value: this.value
  53377. }
  53378. ];
  53379. var dataType;
  53380. if (typeof this.value === "number") {
  53381. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53382. }
  53383. else if (this.value instanceof BABYLON.Color3) {
  53384. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53385. }
  53386. else if (this.value instanceof BABYLON.Vector3) {
  53387. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53388. }
  53389. else if (this.value instanceof BABYLON.Matrix) {
  53390. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53391. }
  53392. else if (this.value instanceof BABYLON.Quaternion) {
  53393. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53394. }
  53395. else {
  53396. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53397. return;
  53398. }
  53399. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53400. animation.setKeys(keys);
  53401. if (this.stopOtherAnimations) {
  53402. scene.stopAnimation(this._effectiveTarget);
  53403. }
  53404. var wrapper = function () {
  53405. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53406. if (_this.onInterpolationDone) {
  53407. _this.onInterpolationDone();
  53408. }
  53409. };
  53410. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53411. };
  53412. InterpolateValueAction.prototype.serialize = function (parent) {
  53413. return _super.prototype._serialize.call(this, {
  53414. name: "InterpolateValueAction",
  53415. properties: [
  53416. BABYLON.Action._GetTargetProperty(this._target),
  53417. { name: "propertyPath", value: this.propertyPath },
  53418. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53419. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53420. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53421. ]
  53422. }, parent);
  53423. };
  53424. return InterpolateValueAction;
  53425. }(BABYLON.Action));
  53426. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53427. })(BABYLON || (BABYLON = {}));
  53428. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53429. var BABYLON;
  53430. (function (BABYLON) {
  53431. var SwitchBooleanAction = /** @class */ (function (_super) {
  53432. __extends(SwitchBooleanAction, _super);
  53433. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53434. var _this = _super.call(this, triggerOptions, condition) || this;
  53435. _this.propertyPath = propertyPath;
  53436. _this._target = _this._effectiveTarget = target;
  53437. return _this;
  53438. }
  53439. /** @hidden */
  53440. SwitchBooleanAction.prototype._prepare = function () {
  53441. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53442. this._property = this._getProperty(this.propertyPath);
  53443. };
  53444. SwitchBooleanAction.prototype.execute = function () {
  53445. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53446. };
  53447. SwitchBooleanAction.prototype.serialize = function (parent) {
  53448. return _super.prototype._serialize.call(this, {
  53449. name: "SwitchBooleanAction",
  53450. properties: [
  53451. BABYLON.Action._GetTargetProperty(this._target),
  53452. { name: "propertyPath", value: this.propertyPath }
  53453. ]
  53454. }, parent);
  53455. };
  53456. return SwitchBooleanAction;
  53457. }(BABYLON.Action));
  53458. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53459. var SetStateAction = /** @class */ (function (_super) {
  53460. __extends(SetStateAction, _super);
  53461. function SetStateAction(triggerOptions, target, value, condition) {
  53462. var _this = _super.call(this, triggerOptions, condition) || this;
  53463. _this.value = value;
  53464. _this._target = target;
  53465. return _this;
  53466. }
  53467. SetStateAction.prototype.execute = function () {
  53468. this._target.state = this.value;
  53469. };
  53470. SetStateAction.prototype.serialize = function (parent) {
  53471. return _super.prototype._serialize.call(this, {
  53472. name: "SetStateAction",
  53473. properties: [
  53474. BABYLON.Action._GetTargetProperty(this._target),
  53475. { name: "value", value: this.value }
  53476. ]
  53477. }, parent);
  53478. };
  53479. return SetStateAction;
  53480. }(BABYLON.Action));
  53481. BABYLON.SetStateAction = SetStateAction;
  53482. var SetValueAction = /** @class */ (function (_super) {
  53483. __extends(SetValueAction, _super);
  53484. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53485. var _this = _super.call(this, triggerOptions, condition) || this;
  53486. _this.propertyPath = propertyPath;
  53487. _this.value = value;
  53488. _this._target = _this._effectiveTarget = target;
  53489. return _this;
  53490. }
  53491. /** @hidden */
  53492. SetValueAction.prototype._prepare = function () {
  53493. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53494. this._property = this._getProperty(this.propertyPath);
  53495. };
  53496. SetValueAction.prototype.execute = function () {
  53497. this._effectiveTarget[this._property] = this.value;
  53498. if (this._target.markAsDirty) {
  53499. this._target.markAsDirty(this._property);
  53500. }
  53501. };
  53502. SetValueAction.prototype.serialize = function (parent) {
  53503. return _super.prototype._serialize.call(this, {
  53504. name: "SetValueAction",
  53505. properties: [
  53506. BABYLON.Action._GetTargetProperty(this._target),
  53507. { name: "propertyPath", value: this.propertyPath },
  53508. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53509. ]
  53510. }, parent);
  53511. };
  53512. return SetValueAction;
  53513. }(BABYLON.Action));
  53514. BABYLON.SetValueAction = SetValueAction;
  53515. var IncrementValueAction = /** @class */ (function (_super) {
  53516. __extends(IncrementValueAction, _super);
  53517. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53518. var _this = _super.call(this, triggerOptions, condition) || this;
  53519. _this.propertyPath = propertyPath;
  53520. _this.value = value;
  53521. _this._target = _this._effectiveTarget = target;
  53522. return _this;
  53523. }
  53524. /** @hidden */
  53525. IncrementValueAction.prototype._prepare = function () {
  53526. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53527. this._property = this._getProperty(this.propertyPath);
  53528. if (typeof this._effectiveTarget[this._property] !== "number") {
  53529. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53530. }
  53531. };
  53532. IncrementValueAction.prototype.execute = function () {
  53533. this._effectiveTarget[this._property] += this.value;
  53534. if (this._target.markAsDirty) {
  53535. this._target.markAsDirty(this._property);
  53536. }
  53537. };
  53538. IncrementValueAction.prototype.serialize = function (parent) {
  53539. return _super.prototype._serialize.call(this, {
  53540. name: "IncrementValueAction",
  53541. properties: [
  53542. BABYLON.Action._GetTargetProperty(this._target),
  53543. { name: "propertyPath", value: this.propertyPath },
  53544. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53545. ]
  53546. }, parent);
  53547. };
  53548. return IncrementValueAction;
  53549. }(BABYLON.Action));
  53550. BABYLON.IncrementValueAction = IncrementValueAction;
  53551. var PlayAnimationAction = /** @class */ (function (_super) {
  53552. __extends(PlayAnimationAction, _super);
  53553. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53554. var _this = _super.call(this, triggerOptions, condition) || this;
  53555. _this.from = from;
  53556. _this.to = to;
  53557. _this.loop = loop;
  53558. _this._target = target;
  53559. return _this;
  53560. }
  53561. /** @hidden */
  53562. PlayAnimationAction.prototype._prepare = function () {
  53563. };
  53564. PlayAnimationAction.prototype.execute = function () {
  53565. var scene = this._actionManager.getScene();
  53566. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53567. };
  53568. PlayAnimationAction.prototype.serialize = function (parent) {
  53569. return _super.prototype._serialize.call(this, {
  53570. name: "PlayAnimationAction",
  53571. properties: [
  53572. BABYLON.Action._GetTargetProperty(this._target),
  53573. { name: "from", value: String(this.from) },
  53574. { name: "to", value: String(this.to) },
  53575. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53576. ]
  53577. }, parent);
  53578. };
  53579. return PlayAnimationAction;
  53580. }(BABYLON.Action));
  53581. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53582. var StopAnimationAction = /** @class */ (function (_super) {
  53583. __extends(StopAnimationAction, _super);
  53584. function StopAnimationAction(triggerOptions, target, condition) {
  53585. var _this = _super.call(this, triggerOptions, condition) || this;
  53586. _this._target = target;
  53587. return _this;
  53588. }
  53589. /** @hidden */
  53590. StopAnimationAction.prototype._prepare = function () {
  53591. };
  53592. StopAnimationAction.prototype.execute = function () {
  53593. var scene = this._actionManager.getScene();
  53594. scene.stopAnimation(this._target);
  53595. };
  53596. StopAnimationAction.prototype.serialize = function (parent) {
  53597. return _super.prototype._serialize.call(this, {
  53598. name: "StopAnimationAction",
  53599. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53600. }, parent);
  53601. };
  53602. return StopAnimationAction;
  53603. }(BABYLON.Action));
  53604. BABYLON.StopAnimationAction = StopAnimationAction;
  53605. var DoNothingAction = /** @class */ (function (_super) {
  53606. __extends(DoNothingAction, _super);
  53607. function DoNothingAction(triggerOptions, condition) {
  53608. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53609. return _super.call(this, triggerOptions, condition) || this;
  53610. }
  53611. DoNothingAction.prototype.execute = function () {
  53612. };
  53613. DoNothingAction.prototype.serialize = function (parent) {
  53614. return _super.prototype._serialize.call(this, {
  53615. name: "DoNothingAction",
  53616. properties: []
  53617. }, parent);
  53618. };
  53619. return DoNothingAction;
  53620. }(BABYLON.Action));
  53621. BABYLON.DoNothingAction = DoNothingAction;
  53622. var CombineAction = /** @class */ (function (_super) {
  53623. __extends(CombineAction, _super);
  53624. function CombineAction(triggerOptions, children, condition) {
  53625. var _this = _super.call(this, triggerOptions, condition) || this;
  53626. _this.children = children;
  53627. return _this;
  53628. }
  53629. /** @hidden */
  53630. CombineAction.prototype._prepare = function () {
  53631. for (var index = 0; index < this.children.length; index++) {
  53632. this.children[index]._actionManager = this._actionManager;
  53633. this.children[index]._prepare();
  53634. }
  53635. };
  53636. CombineAction.prototype.execute = function (evt) {
  53637. for (var index = 0; index < this.children.length; index++) {
  53638. this.children[index].execute(evt);
  53639. }
  53640. };
  53641. CombineAction.prototype.serialize = function (parent) {
  53642. var serializationObject = _super.prototype._serialize.call(this, {
  53643. name: "CombineAction",
  53644. properties: [],
  53645. combine: []
  53646. }, parent);
  53647. for (var i = 0; i < this.children.length; i++) {
  53648. serializationObject.combine.push(this.children[i].serialize(null));
  53649. }
  53650. return serializationObject;
  53651. };
  53652. return CombineAction;
  53653. }(BABYLON.Action));
  53654. BABYLON.CombineAction = CombineAction;
  53655. var ExecuteCodeAction = /** @class */ (function (_super) {
  53656. __extends(ExecuteCodeAction, _super);
  53657. function ExecuteCodeAction(triggerOptions, func, condition) {
  53658. var _this = _super.call(this, triggerOptions, condition) || this;
  53659. _this.func = func;
  53660. return _this;
  53661. }
  53662. ExecuteCodeAction.prototype.execute = function (evt) {
  53663. this.func(evt);
  53664. };
  53665. return ExecuteCodeAction;
  53666. }(BABYLON.Action));
  53667. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53668. var SetParentAction = /** @class */ (function (_super) {
  53669. __extends(SetParentAction, _super);
  53670. function SetParentAction(triggerOptions, target, parent, condition) {
  53671. var _this = _super.call(this, triggerOptions, condition) || this;
  53672. _this._target = target;
  53673. _this._parent = parent;
  53674. return _this;
  53675. }
  53676. /** @hidden */
  53677. SetParentAction.prototype._prepare = function () {
  53678. };
  53679. SetParentAction.prototype.execute = function () {
  53680. if (this._target.parent === this._parent) {
  53681. return;
  53682. }
  53683. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53684. invertParentWorldMatrix.invert();
  53685. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53686. this._target.parent = this._parent;
  53687. };
  53688. SetParentAction.prototype.serialize = function (parent) {
  53689. return _super.prototype._serialize.call(this, {
  53690. name: "SetParentAction",
  53691. properties: [
  53692. BABYLON.Action._GetTargetProperty(this._target),
  53693. BABYLON.Action._GetTargetProperty(this._parent),
  53694. ]
  53695. }, parent);
  53696. };
  53697. return SetParentAction;
  53698. }(BABYLON.Action));
  53699. BABYLON.SetParentAction = SetParentAction;
  53700. var PlaySoundAction = /** @class */ (function (_super) {
  53701. __extends(PlaySoundAction, _super);
  53702. function PlaySoundAction(triggerOptions, sound, condition) {
  53703. var _this = _super.call(this, triggerOptions, condition) || this;
  53704. _this._sound = sound;
  53705. return _this;
  53706. }
  53707. /** @hidden */
  53708. PlaySoundAction.prototype._prepare = function () {
  53709. };
  53710. PlaySoundAction.prototype.execute = function () {
  53711. if (this._sound !== undefined)
  53712. this._sound.play();
  53713. };
  53714. PlaySoundAction.prototype.serialize = function (parent) {
  53715. return _super.prototype._serialize.call(this, {
  53716. name: "PlaySoundAction",
  53717. properties: [{ name: "sound", value: this._sound.name }]
  53718. }, parent);
  53719. };
  53720. return PlaySoundAction;
  53721. }(BABYLON.Action));
  53722. BABYLON.PlaySoundAction = PlaySoundAction;
  53723. var StopSoundAction = /** @class */ (function (_super) {
  53724. __extends(StopSoundAction, _super);
  53725. function StopSoundAction(triggerOptions, sound, condition) {
  53726. var _this = _super.call(this, triggerOptions, condition) || this;
  53727. _this._sound = sound;
  53728. return _this;
  53729. }
  53730. /** @hidden */
  53731. StopSoundAction.prototype._prepare = function () {
  53732. };
  53733. StopSoundAction.prototype.execute = function () {
  53734. if (this._sound !== undefined)
  53735. this._sound.stop();
  53736. };
  53737. StopSoundAction.prototype.serialize = function (parent) {
  53738. return _super.prototype._serialize.call(this, {
  53739. name: "StopSoundAction",
  53740. properties: [{ name: "sound", value: this._sound.name }]
  53741. }, parent);
  53742. };
  53743. return StopSoundAction;
  53744. }(BABYLON.Action));
  53745. BABYLON.StopSoundAction = StopSoundAction;
  53746. })(BABYLON || (BABYLON = {}));
  53747. //# sourceMappingURL=babylon.directActions.js.map
  53748. var BABYLON;
  53749. (function (BABYLON) {
  53750. var SpriteManager = /** @class */ (function () {
  53751. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53752. if (epsilon === void 0) { epsilon = 0.01; }
  53753. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53754. this.name = name;
  53755. this.sprites = new Array();
  53756. this.renderingGroupId = 0;
  53757. this.layerMask = 0x0FFFFFFF;
  53758. this.fogEnabled = true;
  53759. this.isPickable = false;
  53760. /**
  53761. * An event triggered when the manager is disposed.
  53762. */
  53763. this.onDisposeObservable = new BABYLON.Observable();
  53764. this._vertexBuffers = {};
  53765. this._capacity = capacity;
  53766. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53767. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53768. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53769. if (cellSize.width && cellSize.height) {
  53770. this.cellWidth = cellSize.width;
  53771. this.cellHeight = cellSize.height;
  53772. }
  53773. else if (cellSize !== undefined) {
  53774. this.cellWidth = cellSize;
  53775. this.cellHeight = cellSize;
  53776. }
  53777. else {
  53778. return;
  53779. }
  53780. this._epsilon = epsilon;
  53781. this._scene = scene;
  53782. this._scene.spriteManagers.push(this);
  53783. var indices = [];
  53784. var index = 0;
  53785. for (var count = 0; count < capacity; count++) {
  53786. indices.push(index);
  53787. indices.push(index + 1);
  53788. indices.push(index + 2);
  53789. indices.push(index);
  53790. indices.push(index + 2);
  53791. indices.push(index + 3);
  53792. index += 4;
  53793. }
  53794. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53795. // VBO
  53796. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53797. this._vertexData = new Float32Array(capacity * 16 * 4);
  53798. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53799. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53800. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53801. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53802. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53803. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53804. this._vertexBuffers["options"] = options;
  53805. this._vertexBuffers["cellInfo"] = cellInfo;
  53806. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53807. // Effects
  53808. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53809. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53810. }
  53811. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53812. set: function (callback) {
  53813. if (this._onDisposeObserver) {
  53814. this.onDisposeObservable.remove(this._onDisposeObserver);
  53815. }
  53816. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53817. },
  53818. enumerable: true,
  53819. configurable: true
  53820. });
  53821. Object.defineProperty(SpriteManager.prototype, "texture", {
  53822. get: function () {
  53823. return this._spriteTexture;
  53824. },
  53825. set: function (value) {
  53826. this._spriteTexture = value;
  53827. },
  53828. enumerable: true,
  53829. configurable: true
  53830. });
  53831. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53832. var arrayOffset = index * 16;
  53833. if (offsetX === 0)
  53834. offsetX = this._epsilon;
  53835. else if (offsetX === 1)
  53836. offsetX = 1 - this._epsilon;
  53837. if (offsetY === 0)
  53838. offsetY = this._epsilon;
  53839. else if (offsetY === 1)
  53840. offsetY = 1 - this._epsilon;
  53841. this._vertexData[arrayOffset] = sprite.position.x;
  53842. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53843. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53844. this._vertexData[arrayOffset + 3] = sprite.angle;
  53845. this._vertexData[arrayOffset + 4] = sprite.width;
  53846. this._vertexData[arrayOffset + 5] = sprite.height;
  53847. this._vertexData[arrayOffset + 6] = offsetX;
  53848. this._vertexData[arrayOffset + 7] = offsetY;
  53849. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53850. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53851. var offset = (sprite.cellIndex / rowSize) >> 0;
  53852. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53853. this._vertexData[arrayOffset + 11] = offset;
  53854. // Color
  53855. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53856. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53857. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53858. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53859. };
  53860. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53861. var count = Math.min(this._capacity, this.sprites.length);
  53862. var min = BABYLON.Vector3.Zero();
  53863. var max = BABYLON.Vector3.Zero();
  53864. var distance = Number.MAX_VALUE;
  53865. var currentSprite = null;
  53866. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53867. var cameraView = camera.getViewMatrix();
  53868. for (var index = 0; index < count; index++) {
  53869. var sprite = this.sprites[index];
  53870. if (!sprite) {
  53871. continue;
  53872. }
  53873. if (predicate) {
  53874. if (!predicate(sprite)) {
  53875. continue;
  53876. }
  53877. }
  53878. else if (!sprite.isPickable) {
  53879. continue;
  53880. }
  53881. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53882. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53883. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53884. if (ray.intersectsBoxMinMax(min, max)) {
  53885. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53886. if (distance > currentDistance) {
  53887. distance = currentDistance;
  53888. currentSprite = sprite;
  53889. if (fastCheck) {
  53890. break;
  53891. }
  53892. }
  53893. }
  53894. }
  53895. if (currentSprite) {
  53896. var result = new BABYLON.PickingInfo();
  53897. result.hit = true;
  53898. result.pickedSprite = currentSprite;
  53899. result.distance = distance;
  53900. return result;
  53901. }
  53902. return null;
  53903. };
  53904. SpriteManager.prototype.render = function () {
  53905. // Check
  53906. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53907. return;
  53908. var engine = this._scene.getEngine();
  53909. var baseSize = this._spriteTexture.getBaseSize();
  53910. // Sprites
  53911. var deltaTime = engine.getDeltaTime();
  53912. var max = Math.min(this._capacity, this.sprites.length);
  53913. var rowSize = baseSize.width / this.cellWidth;
  53914. var offset = 0;
  53915. for (var index = 0; index < max; index++) {
  53916. var sprite = this.sprites[index];
  53917. if (!sprite || !sprite.isVisible) {
  53918. continue;
  53919. }
  53920. sprite._animate(deltaTime);
  53921. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53922. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53923. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53924. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53925. }
  53926. this._buffer.update(this._vertexData);
  53927. // Render
  53928. var effect = this._effectBase;
  53929. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53930. effect = this._effectFog;
  53931. }
  53932. engine.enableEffect(effect);
  53933. var viewMatrix = this._scene.getViewMatrix();
  53934. effect.setTexture("diffuseSampler", this._spriteTexture);
  53935. effect.setMatrix("view", viewMatrix);
  53936. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53937. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53938. // Fog
  53939. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53940. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53941. effect.setColor3("vFogColor", this._scene.fogColor);
  53942. }
  53943. // VBOs
  53944. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53945. // Draw order
  53946. engine.setDepthFunctionToLessOrEqual();
  53947. effect.setBool("alphaTest", true);
  53948. engine.setColorWrite(false);
  53949. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53950. engine.setColorWrite(true);
  53951. effect.setBool("alphaTest", false);
  53952. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53953. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53954. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53955. };
  53956. SpriteManager.prototype.dispose = function () {
  53957. if (this._buffer) {
  53958. this._buffer.dispose();
  53959. this._buffer = null;
  53960. }
  53961. if (this._indexBuffer) {
  53962. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53963. this._indexBuffer = null;
  53964. }
  53965. if (this._spriteTexture) {
  53966. this._spriteTexture.dispose();
  53967. this._spriteTexture = null;
  53968. }
  53969. // Remove from scene
  53970. var index = this._scene.spriteManagers.indexOf(this);
  53971. this._scene.spriteManagers.splice(index, 1);
  53972. // Callback
  53973. this.onDisposeObservable.notifyObservers(this);
  53974. this.onDisposeObservable.clear();
  53975. };
  53976. return SpriteManager;
  53977. }());
  53978. BABYLON.SpriteManager = SpriteManager;
  53979. })(BABYLON || (BABYLON = {}));
  53980. //# sourceMappingURL=babylon.spriteManager.js.map
  53981. var BABYLON;
  53982. (function (BABYLON) {
  53983. var Sprite = /** @class */ (function () {
  53984. function Sprite(name, manager) {
  53985. this.name = name;
  53986. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53987. this.width = 1.0;
  53988. this.height = 1.0;
  53989. this.angle = 0;
  53990. this.cellIndex = 0;
  53991. this.invertU = 0;
  53992. this.invertV = 0;
  53993. this.animations = new Array();
  53994. this.isPickable = false;
  53995. this._animationStarted = false;
  53996. this._loopAnimation = false;
  53997. this._fromIndex = 0;
  53998. this._toIndex = 0;
  53999. this._delay = 0;
  54000. this._direction = 1;
  54001. this._time = 0;
  54002. /**
  54003. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54004. */
  54005. this.isVisible = true;
  54006. this._manager = manager;
  54007. this._manager.sprites.push(this);
  54008. this.position = BABYLON.Vector3.Zero();
  54009. }
  54010. Object.defineProperty(Sprite.prototype, "size", {
  54011. get: function () {
  54012. return this.width;
  54013. },
  54014. set: function (value) {
  54015. this.width = value;
  54016. this.height = value;
  54017. },
  54018. enumerable: true,
  54019. configurable: true
  54020. });
  54021. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54022. this._fromIndex = from;
  54023. this._toIndex = to;
  54024. this._loopAnimation = loop;
  54025. this._delay = delay;
  54026. this._animationStarted = true;
  54027. this._direction = from < to ? 1 : -1;
  54028. this.cellIndex = from;
  54029. this._time = 0;
  54030. this._onAnimationEnd = onAnimationEnd;
  54031. };
  54032. Sprite.prototype.stopAnimation = function () {
  54033. this._animationStarted = false;
  54034. };
  54035. /** @hidden */
  54036. Sprite.prototype._animate = function (deltaTime) {
  54037. if (!this._animationStarted)
  54038. return;
  54039. this._time += deltaTime;
  54040. if (this._time > this._delay) {
  54041. this._time = this._time % this._delay;
  54042. this.cellIndex += this._direction;
  54043. if (this.cellIndex > this._toIndex) {
  54044. if (this._loopAnimation) {
  54045. this.cellIndex = this._fromIndex;
  54046. }
  54047. else {
  54048. this.cellIndex = this._toIndex;
  54049. this._animationStarted = false;
  54050. if (this._onAnimationEnd) {
  54051. this._onAnimationEnd();
  54052. }
  54053. if (this.disposeWhenFinishedAnimating) {
  54054. this.dispose();
  54055. }
  54056. }
  54057. }
  54058. }
  54059. };
  54060. Sprite.prototype.dispose = function () {
  54061. for (var i = 0; i < this._manager.sprites.length; i++) {
  54062. if (this._manager.sprites[i] == this) {
  54063. this._manager.sprites.splice(i, 1);
  54064. }
  54065. }
  54066. };
  54067. return Sprite;
  54068. }());
  54069. BABYLON.Sprite = Sprite;
  54070. })(BABYLON || (BABYLON = {}));
  54071. //# sourceMappingURL=babylon.sprite.js.map
  54072. var BABYLON;
  54073. (function (BABYLON) {
  54074. var IntersectionInfo = /** @class */ (function () {
  54075. function IntersectionInfo(bu, bv, distance) {
  54076. this.bu = bu;
  54077. this.bv = bv;
  54078. this.distance = distance;
  54079. this.faceId = 0;
  54080. this.subMeshId = 0;
  54081. }
  54082. return IntersectionInfo;
  54083. }());
  54084. BABYLON.IntersectionInfo = IntersectionInfo;
  54085. /**
  54086. * Information about the result of picking within a scene
  54087. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54088. */
  54089. var PickingInfo = /** @class */ (function () {
  54090. function PickingInfo() {
  54091. /**
  54092. * If the pick collided with an object
  54093. */
  54094. this.hit = false;
  54095. /**
  54096. * Distance away where the pick collided
  54097. */
  54098. this.distance = 0;
  54099. /**
  54100. * The location of pick collision
  54101. */
  54102. this.pickedPoint = null;
  54103. /**
  54104. * The mesh corresponding the the pick collision
  54105. */
  54106. this.pickedMesh = null;
  54107. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54108. this.bu = 0;
  54109. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54110. this.bv = 0;
  54111. /** The id of the face on the mesh that was picked */
  54112. this.faceId = -1;
  54113. /** Id of the the submesh that was picked */
  54114. this.subMeshId = 0;
  54115. /** If a sprite was picked, this will be the sprite the pick collided with */
  54116. this.pickedSprite = null;
  54117. /**
  54118. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54119. */
  54120. this.originMesh = null;
  54121. /**
  54122. * The ray that was used to perform the picking.
  54123. */
  54124. this.ray = null;
  54125. }
  54126. /**
  54127. * Gets the normal correspodning to the face the pick collided with
  54128. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54129. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54130. * @returns The normal correspodning to the face the pick collided with
  54131. */
  54132. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54133. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54134. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54135. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54136. return null;
  54137. }
  54138. var indices = this.pickedMesh.getIndices();
  54139. if (!indices) {
  54140. return null;
  54141. }
  54142. var result;
  54143. if (useVerticesNormals) {
  54144. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54145. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54146. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54147. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54148. normal0 = normal0.scale(this.bu);
  54149. normal1 = normal1.scale(this.bv);
  54150. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54151. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54152. }
  54153. else {
  54154. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54155. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54156. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54157. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54158. var p1p2 = vertex1.subtract(vertex2);
  54159. var p3p2 = vertex3.subtract(vertex2);
  54160. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54161. }
  54162. if (useWorldCoordinates) {
  54163. var wm = this.pickedMesh.getWorldMatrix();
  54164. if (this.pickedMesh.nonUniformScaling) {
  54165. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54166. wm = BABYLON.Tmp.Matrix[0];
  54167. wm.setTranslationFromFloats(0, 0, 0);
  54168. wm.invert();
  54169. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54170. wm = BABYLON.Tmp.Matrix[1];
  54171. }
  54172. result = BABYLON.Vector3.TransformNormal(result, wm);
  54173. }
  54174. result.normalize();
  54175. return result;
  54176. };
  54177. /**
  54178. * Gets the texture coordinates of where the pick occured
  54179. * @returns the vector containing the coordnates of the texture
  54180. */
  54181. PickingInfo.prototype.getTextureCoordinates = function () {
  54182. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54183. return null;
  54184. }
  54185. var indices = this.pickedMesh.getIndices();
  54186. if (!indices) {
  54187. return null;
  54188. }
  54189. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54190. if (!uvs) {
  54191. return null;
  54192. }
  54193. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54194. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54195. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54196. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54197. uv1 = uv1.scale(this.bu);
  54198. uv2 = uv2.scale(this.bv);
  54199. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54200. };
  54201. return PickingInfo;
  54202. }());
  54203. BABYLON.PickingInfo = PickingInfo;
  54204. })(BABYLON || (BABYLON = {}));
  54205. //# sourceMappingURL=babylon.pickingInfo.js.map
  54206. var BABYLON;
  54207. (function (BABYLON) {
  54208. var Ray = /** @class */ (function () {
  54209. function Ray(origin, direction, length) {
  54210. if (length === void 0) { length = Number.MAX_VALUE; }
  54211. this.origin = origin;
  54212. this.direction = direction;
  54213. this.length = length;
  54214. }
  54215. // Methods
  54216. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54217. var d = 0.0;
  54218. var maxValue = Number.MAX_VALUE;
  54219. var inv;
  54220. var min;
  54221. var max;
  54222. var temp;
  54223. if (Math.abs(this.direction.x) < 0.0000001) {
  54224. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54225. return false;
  54226. }
  54227. }
  54228. else {
  54229. inv = 1.0 / this.direction.x;
  54230. min = (minimum.x - this.origin.x) * inv;
  54231. max = (maximum.x - this.origin.x) * inv;
  54232. if (max === -Infinity) {
  54233. max = Infinity;
  54234. }
  54235. if (min > max) {
  54236. temp = min;
  54237. min = max;
  54238. max = temp;
  54239. }
  54240. d = Math.max(min, d);
  54241. maxValue = Math.min(max, maxValue);
  54242. if (d > maxValue) {
  54243. return false;
  54244. }
  54245. }
  54246. if (Math.abs(this.direction.y) < 0.0000001) {
  54247. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54248. return false;
  54249. }
  54250. }
  54251. else {
  54252. inv = 1.0 / this.direction.y;
  54253. min = (minimum.y - this.origin.y) * inv;
  54254. max = (maximum.y - this.origin.y) * inv;
  54255. if (max === -Infinity) {
  54256. max = Infinity;
  54257. }
  54258. if (min > max) {
  54259. temp = min;
  54260. min = max;
  54261. max = temp;
  54262. }
  54263. d = Math.max(min, d);
  54264. maxValue = Math.min(max, maxValue);
  54265. if (d > maxValue) {
  54266. return false;
  54267. }
  54268. }
  54269. if (Math.abs(this.direction.z) < 0.0000001) {
  54270. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54271. return false;
  54272. }
  54273. }
  54274. else {
  54275. inv = 1.0 / this.direction.z;
  54276. min = (minimum.z - this.origin.z) * inv;
  54277. max = (maximum.z - this.origin.z) * inv;
  54278. if (max === -Infinity) {
  54279. max = Infinity;
  54280. }
  54281. if (min > max) {
  54282. temp = min;
  54283. min = max;
  54284. max = temp;
  54285. }
  54286. d = Math.max(min, d);
  54287. maxValue = Math.min(max, maxValue);
  54288. if (d > maxValue) {
  54289. return false;
  54290. }
  54291. }
  54292. return true;
  54293. };
  54294. Ray.prototype.intersectsBox = function (box) {
  54295. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54296. };
  54297. Ray.prototype.intersectsSphere = function (sphere) {
  54298. var x = sphere.center.x - this.origin.x;
  54299. var y = sphere.center.y - this.origin.y;
  54300. var z = sphere.center.z - this.origin.z;
  54301. var pyth = (x * x) + (y * y) + (z * z);
  54302. var rr = sphere.radius * sphere.radius;
  54303. if (pyth <= rr) {
  54304. return true;
  54305. }
  54306. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54307. if (dot < 0.0) {
  54308. return false;
  54309. }
  54310. var temp = pyth - (dot * dot);
  54311. return temp <= rr;
  54312. };
  54313. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54314. if (!this._edge1) {
  54315. this._edge1 = BABYLON.Vector3.Zero();
  54316. this._edge2 = BABYLON.Vector3.Zero();
  54317. this._pvec = BABYLON.Vector3.Zero();
  54318. this._tvec = BABYLON.Vector3.Zero();
  54319. this._qvec = BABYLON.Vector3.Zero();
  54320. }
  54321. vertex1.subtractToRef(vertex0, this._edge1);
  54322. vertex2.subtractToRef(vertex0, this._edge2);
  54323. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54324. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54325. if (det === 0) {
  54326. return null;
  54327. }
  54328. var invdet = 1 / det;
  54329. this.origin.subtractToRef(vertex0, this._tvec);
  54330. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54331. if (bu < 0 || bu > 1.0) {
  54332. return null;
  54333. }
  54334. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54335. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54336. if (bv < 0 || bu + bv > 1.0) {
  54337. return null;
  54338. }
  54339. //check if the distance is longer than the predefined length.
  54340. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54341. if (distance > this.length) {
  54342. return null;
  54343. }
  54344. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54345. };
  54346. Ray.prototype.intersectsPlane = function (plane) {
  54347. var distance;
  54348. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54349. if (Math.abs(result1) < 9.99999997475243E-07) {
  54350. return null;
  54351. }
  54352. else {
  54353. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54354. distance = (-plane.d - result2) / result1;
  54355. if (distance < 0.0) {
  54356. if (distance < -9.99999997475243E-07) {
  54357. return null;
  54358. }
  54359. else {
  54360. return 0;
  54361. }
  54362. }
  54363. return distance;
  54364. }
  54365. };
  54366. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54367. var tm = BABYLON.Tmp.Matrix[0];
  54368. mesh.getWorldMatrix().invertToRef(tm);
  54369. if (this._tmpRay) {
  54370. Ray.TransformToRef(this, tm, this._tmpRay);
  54371. }
  54372. else {
  54373. this._tmpRay = Ray.Transform(this, tm);
  54374. }
  54375. return mesh.intersects(this._tmpRay, fastCheck);
  54376. };
  54377. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54378. if (results) {
  54379. results.length = 0;
  54380. }
  54381. else {
  54382. results = [];
  54383. }
  54384. for (var i = 0; i < meshes.length; i++) {
  54385. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54386. if (pickInfo.hit) {
  54387. results.push(pickInfo);
  54388. }
  54389. }
  54390. results.sort(this._comparePickingInfo);
  54391. return results;
  54392. };
  54393. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54394. if (pickingInfoA.distance < pickingInfoB.distance) {
  54395. return -1;
  54396. }
  54397. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54398. return 1;
  54399. }
  54400. else {
  54401. return 0;
  54402. }
  54403. };
  54404. /**
  54405. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54406. * @param sega the first point of the segment to test the intersection against
  54407. * @param segb the second point of the segment to test the intersection against
  54408. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54409. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54410. */
  54411. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54412. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54413. var u = segb.subtract(sega);
  54414. var v = rsegb.subtract(this.origin);
  54415. var w = sega.subtract(this.origin);
  54416. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54417. var b = BABYLON.Vector3.Dot(u, v);
  54418. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54419. var d = BABYLON.Vector3.Dot(u, w);
  54420. var e = BABYLON.Vector3.Dot(v, w);
  54421. var D = a * c - b * b; // always >= 0
  54422. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54423. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54424. // compute the line parameters of the two closest points
  54425. if (D < Ray.smallnum) { // the lines are almost parallel
  54426. sN = 0.0; // force using point P0 on segment S1
  54427. sD = 1.0; // to prevent possible division by 0.0 later
  54428. tN = e;
  54429. tD = c;
  54430. }
  54431. else { // get the closest points on the infinite lines
  54432. sN = (b * e - c * d);
  54433. tN = (a * e - b * d);
  54434. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54435. sN = 0.0;
  54436. tN = e;
  54437. tD = c;
  54438. }
  54439. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54440. sN = sD;
  54441. tN = e + b;
  54442. tD = c;
  54443. }
  54444. }
  54445. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54446. tN = 0.0;
  54447. // recompute sc for this edge
  54448. if (-d < 0.0) {
  54449. sN = 0.0;
  54450. }
  54451. else if (-d > a)
  54452. sN = sD;
  54453. else {
  54454. sN = -d;
  54455. sD = a;
  54456. }
  54457. }
  54458. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54459. tN = tD;
  54460. // recompute sc for this edge
  54461. if ((-d + b) < 0.0) {
  54462. sN = 0;
  54463. }
  54464. else if ((-d + b) > a) {
  54465. sN = sD;
  54466. }
  54467. else {
  54468. sN = (-d + b);
  54469. sD = a;
  54470. }
  54471. }
  54472. // finally do the division to get sc and tc
  54473. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54474. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54475. // get the difference of the two closest points
  54476. var qtc = v.multiplyByFloats(tc, tc, tc);
  54477. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54478. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54479. if (isIntersected) {
  54480. return qtc.length();
  54481. }
  54482. return -1;
  54483. };
  54484. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54485. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54486. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54487. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54488. this.direction.normalize();
  54489. return this;
  54490. };
  54491. // Statics
  54492. Ray.Zero = function () {
  54493. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54494. };
  54495. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54496. var result = Ray.Zero();
  54497. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54498. };
  54499. /**
  54500. * 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
  54501. * transformed to the given world matrix.
  54502. * @param origin The origin point
  54503. * @param end The end point
  54504. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54505. */
  54506. Ray.CreateNewFromTo = function (origin, end, world) {
  54507. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54508. var direction = end.subtract(origin);
  54509. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54510. direction.normalize();
  54511. return Ray.Transform(new Ray(origin, direction, length), world);
  54512. };
  54513. Ray.Transform = function (ray, matrix) {
  54514. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54515. Ray.TransformToRef(ray, matrix, result);
  54516. return result;
  54517. };
  54518. Ray.TransformToRef = function (ray, matrix, result) {
  54519. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54520. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54521. result.length = ray.length;
  54522. var dir = result.direction;
  54523. var len = dir.length();
  54524. if (!(len === 0 || len === 1)) {
  54525. var num = 1.0 / len;
  54526. dir.x *= num;
  54527. dir.y *= num;
  54528. dir.z *= num;
  54529. result.length *= len;
  54530. }
  54531. };
  54532. Ray.smallnum = 0.00000001;
  54533. Ray.rayl = 10e8;
  54534. return Ray;
  54535. }());
  54536. BABYLON.Ray = Ray;
  54537. })(BABYLON || (BABYLON = {}));
  54538. //# sourceMappingURL=babylon.ray.js.map
  54539. var BABYLON;
  54540. (function (BABYLON) {
  54541. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54542. if (boxMin.x > sphereCenter.x + sphereRadius)
  54543. return false;
  54544. if (sphereCenter.x - sphereRadius > boxMax.x)
  54545. return false;
  54546. if (boxMin.y > sphereCenter.y + sphereRadius)
  54547. return false;
  54548. if (sphereCenter.y - sphereRadius > boxMax.y)
  54549. return false;
  54550. if (boxMin.z > sphereCenter.z + sphereRadius)
  54551. return false;
  54552. if (sphereCenter.z - sphereRadius > boxMax.z)
  54553. return false;
  54554. return true;
  54555. };
  54556. var getLowestRoot = (function () {
  54557. var result = { root: 0, found: false };
  54558. return function (a, b, c, maxR) {
  54559. result.root = 0;
  54560. result.found = false;
  54561. var determinant = b * b - 4.0 * a * c;
  54562. if (determinant < 0)
  54563. return result;
  54564. var sqrtD = Math.sqrt(determinant);
  54565. var r1 = (-b - sqrtD) / (2.0 * a);
  54566. var r2 = (-b + sqrtD) / (2.0 * a);
  54567. if (r1 > r2) {
  54568. var temp = r2;
  54569. r2 = r1;
  54570. r1 = temp;
  54571. }
  54572. if (r1 > 0 && r1 < maxR) {
  54573. result.root = r1;
  54574. result.found = true;
  54575. return result;
  54576. }
  54577. if (r2 > 0 && r2 < maxR) {
  54578. result.root = r2;
  54579. result.found = true;
  54580. return result;
  54581. }
  54582. return result;
  54583. };
  54584. })();
  54585. var Collider = /** @class */ (function () {
  54586. function Collider() {
  54587. this._collisionPoint = BABYLON.Vector3.Zero();
  54588. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54589. this._tempVector = BABYLON.Vector3.Zero();
  54590. this._tempVector2 = BABYLON.Vector3.Zero();
  54591. this._tempVector3 = BABYLON.Vector3.Zero();
  54592. this._tempVector4 = BABYLON.Vector3.Zero();
  54593. this._edge = BABYLON.Vector3.Zero();
  54594. this._baseToVertex = BABYLON.Vector3.Zero();
  54595. this._destinationPoint = BABYLON.Vector3.Zero();
  54596. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54597. this._displacementVector = BABYLON.Vector3.Zero();
  54598. /** @hidden */
  54599. this._radius = BABYLON.Vector3.One();
  54600. /** @hidden */
  54601. this._retry = 0;
  54602. /** @hidden */
  54603. this._basePointWorld = BABYLON.Vector3.Zero();
  54604. this._velocityWorld = BABYLON.Vector3.Zero();
  54605. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54606. this._collisionMask = -1;
  54607. }
  54608. Object.defineProperty(Collider.prototype, "collisionMask", {
  54609. get: function () {
  54610. return this._collisionMask;
  54611. },
  54612. set: function (mask) {
  54613. this._collisionMask = !isNaN(mask) ? mask : -1;
  54614. },
  54615. enumerable: true,
  54616. configurable: true
  54617. });
  54618. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54619. /**
  54620. * Gets the plane normal used to compute the sliding response (in local space)
  54621. */
  54622. get: function () {
  54623. return this._slidePlaneNormal;
  54624. },
  54625. enumerable: true,
  54626. configurable: true
  54627. });
  54628. // Methods
  54629. /** @hidden */
  54630. Collider.prototype._initialize = function (source, dir, e) {
  54631. this._velocity = dir;
  54632. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54633. this._basePoint = source;
  54634. source.multiplyToRef(this._radius, this._basePointWorld);
  54635. dir.multiplyToRef(this._radius, this._velocityWorld);
  54636. this._velocityWorldLength = this._velocityWorld.length();
  54637. this._epsilon = e;
  54638. this.collisionFound = false;
  54639. };
  54640. /** @hidden */
  54641. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54642. pa.subtractToRef(point, this._tempVector);
  54643. pb.subtractToRef(point, this._tempVector2);
  54644. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54645. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54646. if (d < 0)
  54647. return false;
  54648. pc.subtractToRef(point, this._tempVector3);
  54649. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54650. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54651. if (d < 0)
  54652. return false;
  54653. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54654. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54655. return d >= 0;
  54656. };
  54657. /** @hidden */
  54658. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54659. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54660. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54661. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54662. return false;
  54663. }
  54664. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54665. return false;
  54666. return true;
  54667. };
  54668. /** @hidden */
  54669. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54670. var t0;
  54671. var embeddedInPlane = false;
  54672. //defensive programming, actually not needed.
  54673. if (!trianglePlaneArray) {
  54674. trianglePlaneArray = [];
  54675. }
  54676. if (!trianglePlaneArray[faceIndex]) {
  54677. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54678. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54679. }
  54680. var trianglePlane = trianglePlaneArray[faceIndex];
  54681. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54682. return;
  54683. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54684. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54685. if (normalDotVelocity == 0) {
  54686. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54687. return;
  54688. embeddedInPlane = true;
  54689. t0 = 0;
  54690. }
  54691. else {
  54692. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54693. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54694. if (t0 > t1) {
  54695. var temp = t1;
  54696. t1 = t0;
  54697. t0 = temp;
  54698. }
  54699. if (t0 > 1.0 || t1 < 0.0)
  54700. return;
  54701. if (t0 < 0)
  54702. t0 = 0;
  54703. if (t0 > 1.0)
  54704. t0 = 1.0;
  54705. }
  54706. this._collisionPoint.copyFromFloats(0, 0, 0);
  54707. var found = false;
  54708. var t = 1.0;
  54709. if (!embeddedInPlane) {
  54710. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54711. this._velocity.scaleToRef(t0, this._tempVector);
  54712. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54713. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54714. found = true;
  54715. t = t0;
  54716. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54717. }
  54718. }
  54719. if (!found) {
  54720. var velocitySquaredLength = this._velocity.lengthSquared();
  54721. var a = velocitySquaredLength;
  54722. this._basePoint.subtractToRef(p1, this._tempVector);
  54723. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54724. var c = this._tempVector.lengthSquared() - 1.0;
  54725. var lowestRoot = getLowestRoot(a, b, c, t);
  54726. if (lowestRoot.found) {
  54727. t = lowestRoot.root;
  54728. found = true;
  54729. this._collisionPoint.copyFrom(p1);
  54730. }
  54731. this._basePoint.subtractToRef(p2, this._tempVector);
  54732. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54733. c = this._tempVector.lengthSquared() - 1.0;
  54734. lowestRoot = getLowestRoot(a, b, c, t);
  54735. if (lowestRoot.found) {
  54736. t = lowestRoot.root;
  54737. found = true;
  54738. this._collisionPoint.copyFrom(p2);
  54739. }
  54740. this._basePoint.subtractToRef(p3, this._tempVector);
  54741. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54742. c = this._tempVector.lengthSquared() - 1.0;
  54743. lowestRoot = getLowestRoot(a, b, c, t);
  54744. if (lowestRoot.found) {
  54745. t = lowestRoot.root;
  54746. found = true;
  54747. this._collisionPoint.copyFrom(p3);
  54748. }
  54749. p2.subtractToRef(p1, this._edge);
  54750. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54751. var edgeSquaredLength = this._edge.lengthSquared();
  54752. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54753. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54754. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54755. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54756. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54757. lowestRoot = getLowestRoot(a, b, c, t);
  54758. if (lowestRoot.found) {
  54759. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54760. if (f >= 0.0 && f <= 1.0) {
  54761. t = lowestRoot.root;
  54762. found = true;
  54763. this._edge.scaleInPlace(f);
  54764. p1.addToRef(this._edge, this._collisionPoint);
  54765. }
  54766. }
  54767. p3.subtractToRef(p2, this._edge);
  54768. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54769. edgeSquaredLength = this._edge.lengthSquared();
  54770. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54771. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54772. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54773. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54774. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54775. lowestRoot = getLowestRoot(a, b, c, t);
  54776. if (lowestRoot.found) {
  54777. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54778. if (f >= 0.0 && f <= 1.0) {
  54779. t = lowestRoot.root;
  54780. found = true;
  54781. this._edge.scaleInPlace(f);
  54782. p2.addToRef(this._edge, this._collisionPoint);
  54783. }
  54784. }
  54785. p1.subtractToRef(p3, this._edge);
  54786. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54787. edgeSquaredLength = this._edge.lengthSquared();
  54788. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54789. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54790. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54791. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54792. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54793. lowestRoot = getLowestRoot(a, b, c, t);
  54794. if (lowestRoot.found) {
  54795. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54796. if (f >= 0.0 && f <= 1.0) {
  54797. t = lowestRoot.root;
  54798. found = true;
  54799. this._edge.scaleInPlace(f);
  54800. p3.addToRef(this._edge, this._collisionPoint);
  54801. }
  54802. }
  54803. }
  54804. if (found) {
  54805. var distToCollision = t * this._velocity.length();
  54806. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54807. if (!this.intersectionPoint) {
  54808. this.intersectionPoint = this._collisionPoint.clone();
  54809. }
  54810. else {
  54811. this.intersectionPoint.copyFrom(this._collisionPoint);
  54812. }
  54813. this._nearestDistance = distToCollision;
  54814. this.collisionFound = true;
  54815. }
  54816. }
  54817. };
  54818. /** @hidden */
  54819. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54820. for (var i = indexStart; i < indexEnd; i += 3) {
  54821. var p1 = pts[indices[i] - decal];
  54822. var p2 = pts[indices[i + 1] - decal];
  54823. var p3 = pts[indices[i + 2] - decal];
  54824. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54825. }
  54826. };
  54827. /** @hidden */
  54828. Collider.prototype._getResponse = function (pos, vel) {
  54829. pos.addToRef(vel, this._destinationPoint);
  54830. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54831. this._basePoint.addToRef(vel, pos);
  54832. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54833. this._slidePlaneNormal.normalize();
  54834. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54835. pos.addInPlace(this._displacementVector);
  54836. this.intersectionPoint.addInPlace(this._displacementVector);
  54837. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54838. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54839. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54840. };
  54841. return Collider;
  54842. }());
  54843. BABYLON.Collider = Collider;
  54844. })(BABYLON || (BABYLON = {}));
  54845. //# sourceMappingURL=babylon.collider.js.map
  54846. var BABYLON;
  54847. (function (BABYLON) {
  54848. //WebWorker code will be inserted to this variable.
  54849. BABYLON.CollisionWorker = "";
  54850. /** Defines supported task for worker process */
  54851. var WorkerTaskType;
  54852. (function (WorkerTaskType) {
  54853. /** Initialization */
  54854. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54855. /** Update of geometry */
  54856. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54857. /** Evaluate collision */
  54858. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54859. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54860. /** Defines kind of replies returned by worker */
  54861. var WorkerReplyType;
  54862. (function (WorkerReplyType) {
  54863. /** Success */
  54864. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54865. /** Unkown error */
  54866. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54867. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54868. var CollisionCoordinatorWorker = /** @class */ (function () {
  54869. function CollisionCoordinatorWorker() {
  54870. var _this = this;
  54871. this._scaledPosition = BABYLON.Vector3.Zero();
  54872. this._scaledVelocity = BABYLON.Vector3.Zero();
  54873. this.onMeshUpdated = function (transformNode) {
  54874. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54875. };
  54876. this.onGeometryUpdated = function (geometry) {
  54877. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54878. };
  54879. this._afterRender = function () {
  54880. if (!_this._init)
  54881. return;
  54882. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54883. return;
  54884. }
  54885. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54886. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54887. if (_this._runningUpdated > 4) {
  54888. return;
  54889. }
  54890. ++_this._runningUpdated;
  54891. var payload = {
  54892. updatedMeshes: _this._addUpdateMeshesList,
  54893. updatedGeometries: _this._addUpdateGeometriesList,
  54894. removedGeometries: _this._toRemoveGeometryArray,
  54895. removedMeshes: _this._toRemoveMeshesArray
  54896. };
  54897. var message = {
  54898. payload: payload,
  54899. taskType: WorkerTaskType.UPDATE
  54900. };
  54901. var serializable = [];
  54902. for (var id in payload.updatedGeometries) {
  54903. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54904. //prepare transferables
  54905. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54906. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54907. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54908. }
  54909. }
  54910. _this._worker.postMessage(message, serializable);
  54911. _this._addUpdateMeshesList = {};
  54912. _this._addUpdateGeometriesList = {};
  54913. _this._toRemoveGeometryArray = [];
  54914. _this._toRemoveMeshesArray = [];
  54915. };
  54916. this._onMessageFromWorker = function (e) {
  54917. var returnData = e.data;
  54918. if (returnData.error != WorkerReplyType.SUCCESS) {
  54919. //TODO what errors can be returned from the worker?
  54920. BABYLON.Tools.Warn("error returned from worker!");
  54921. return;
  54922. }
  54923. switch (returnData.taskType) {
  54924. case WorkerTaskType.INIT:
  54925. _this._init = true;
  54926. //Update the worked with ALL of the scene's current state
  54927. _this._scene.meshes.forEach(function (mesh) {
  54928. _this.onMeshAdded(mesh);
  54929. });
  54930. _this._scene.getGeometries().forEach(function (geometry) {
  54931. _this.onGeometryAdded(geometry);
  54932. });
  54933. break;
  54934. case WorkerTaskType.UPDATE:
  54935. _this._runningUpdated--;
  54936. break;
  54937. case WorkerTaskType.COLLIDE:
  54938. var returnPayload = returnData.payload;
  54939. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54940. return;
  54941. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54942. if (callback) {
  54943. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54944. if (mesh) {
  54945. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54946. }
  54947. }
  54948. //cleanup
  54949. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54950. break;
  54951. }
  54952. };
  54953. this._collisionsCallbackArray = [];
  54954. this._init = false;
  54955. this._runningUpdated = 0;
  54956. this._addUpdateMeshesList = {};
  54957. this._addUpdateGeometriesList = {};
  54958. this._toRemoveGeometryArray = [];
  54959. this._toRemoveMeshesArray = [];
  54960. }
  54961. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54962. if (!this._init)
  54963. return;
  54964. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54965. return;
  54966. position.divideToRef(collider._radius, this._scaledPosition);
  54967. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54968. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54969. var payload = {
  54970. collider: {
  54971. position: this._scaledPosition.asArray(),
  54972. velocity: this._scaledVelocity.asArray(),
  54973. radius: collider._radius.asArray()
  54974. },
  54975. collisionId: collisionIndex,
  54976. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54977. maximumRetry: maximumRetry
  54978. };
  54979. var message = {
  54980. payload: payload,
  54981. taskType: WorkerTaskType.COLLIDE
  54982. };
  54983. this._worker.postMessage(message);
  54984. };
  54985. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54986. this._scene = scene;
  54987. this._scene.registerAfterRender(this._afterRender);
  54988. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54989. this._worker = new Worker(workerUrl);
  54990. this._worker.onmessage = this._onMessageFromWorker;
  54991. var message = {
  54992. payload: {},
  54993. taskType: WorkerTaskType.INIT
  54994. };
  54995. this._worker.postMessage(message);
  54996. };
  54997. CollisionCoordinatorWorker.prototype.destroy = function () {
  54998. this._scene.unregisterAfterRender(this._afterRender);
  54999. this._worker.terminate();
  55000. };
  55001. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55002. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55003. this.onMeshUpdated(mesh);
  55004. };
  55005. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55006. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55007. };
  55008. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55009. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55010. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55011. this.onGeometryUpdated(geometry);
  55012. };
  55013. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55014. this._toRemoveGeometryArray.push(geometry.id);
  55015. };
  55016. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55017. var submeshes = [];
  55018. if (mesh.subMeshes) {
  55019. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55020. var boundingInfo = sm.getBoundingInfo();
  55021. return {
  55022. position: idx,
  55023. verticesStart: sm.verticesStart,
  55024. verticesCount: sm.verticesCount,
  55025. indexStart: sm.indexStart,
  55026. indexCount: sm.indexCount,
  55027. hasMaterial: !!sm.getMaterial(),
  55028. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55029. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55030. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55031. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55032. };
  55033. });
  55034. }
  55035. var geometryId = null;
  55036. if (mesh instanceof BABYLON.Mesh) {
  55037. var geometry = mesh.geometry;
  55038. geometryId = geometry ? geometry.id : null;
  55039. }
  55040. else if (mesh instanceof BABYLON.InstancedMesh) {
  55041. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55042. geometryId = geometry ? geometry.id : null;
  55043. }
  55044. var boundingInfo = mesh.getBoundingInfo();
  55045. return {
  55046. uniqueId: mesh.uniqueId,
  55047. id: mesh.id,
  55048. name: mesh.name,
  55049. geometryId: geometryId,
  55050. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55051. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55052. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55053. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55054. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55055. subMeshes: submeshes,
  55056. checkCollisions: mesh.checkCollisions
  55057. };
  55058. };
  55059. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55060. return {
  55061. id: geometry.id,
  55062. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55063. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55064. indices: new Uint32Array(geometry.getIndices() || []),
  55065. };
  55066. };
  55067. return CollisionCoordinatorWorker;
  55068. }());
  55069. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55070. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55071. function CollisionCoordinatorLegacy() {
  55072. this._scaledPosition = BABYLON.Vector3.Zero();
  55073. this._scaledVelocity = BABYLON.Vector3.Zero();
  55074. this._finalPosition = BABYLON.Vector3.Zero();
  55075. }
  55076. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55077. position.divideToRef(collider._radius, this._scaledPosition);
  55078. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55079. collider.collidedMesh = null;
  55080. collider._retry = 0;
  55081. collider._initialVelocity = this._scaledVelocity;
  55082. collider._initialPosition = this._scaledPosition;
  55083. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55084. this._finalPosition.multiplyInPlace(collider._radius);
  55085. //run the callback
  55086. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55087. };
  55088. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55089. this._scene = scene;
  55090. };
  55091. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55092. //Legacy need no destruction method.
  55093. };
  55094. //No update in legacy mode
  55095. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55096. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55097. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55098. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55099. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55100. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55101. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55102. if (excludedMesh === void 0) { excludedMesh = null; }
  55103. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55104. if (collider._retry >= maximumRetry) {
  55105. finalPosition.copyFrom(position);
  55106. return;
  55107. }
  55108. // Check if this is a mesh else camera or -1
  55109. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55110. collider._initialize(position, velocity, closeDistance);
  55111. // Check all meshes
  55112. for (var index = 0; index < this._scene.meshes.length; index++) {
  55113. var mesh = this._scene.meshes[index];
  55114. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55115. mesh._checkCollision(collider);
  55116. }
  55117. }
  55118. if (!collider.collisionFound) {
  55119. position.addToRef(velocity, finalPosition);
  55120. return;
  55121. }
  55122. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55123. collider._getResponse(position, velocity);
  55124. }
  55125. if (velocity.length() <= closeDistance) {
  55126. finalPosition.copyFrom(position);
  55127. return;
  55128. }
  55129. collider._retry++;
  55130. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55131. };
  55132. return CollisionCoordinatorLegacy;
  55133. }());
  55134. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55135. })(BABYLON || (BABYLON = {}));
  55136. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55137. var BABYLON;
  55138. (function (BABYLON) {
  55139. /**
  55140. * A particle represents one of the element emitted by a particle system.
  55141. * This is mainly define by its coordinates, direction, velocity and age.
  55142. */
  55143. var Particle = /** @class */ (function () {
  55144. /**
  55145. * Creates a new instance Particle
  55146. * @param particleSystem the particle system the particle belongs to
  55147. */
  55148. function Particle(
  55149. /**
  55150. * particleSystem the particle system the particle belongs to.
  55151. */
  55152. particleSystem) {
  55153. this.particleSystem = particleSystem;
  55154. /**
  55155. * The world position of the particle in the scene.
  55156. */
  55157. this.position = BABYLON.Vector3.Zero();
  55158. /**
  55159. * The world direction of the particle in the scene.
  55160. */
  55161. this.direction = BABYLON.Vector3.Zero();
  55162. /**
  55163. * The color of the particle.
  55164. */
  55165. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55166. /**
  55167. * The color change of the particle per step.
  55168. */
  55169. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55170. /**
  55171. * Defines how long will the life of the particle be.
  55172. */
  55173. this.lifeTime = 1.0;
  55174. /**
  55175. * The current age of the particle.
  55176. */
  55177. this.age = 0;
  55178. /**
  55179. * The current size of the particle.
  55180. */
  55181. this.size = 0;
  55182. /**
  55183. * The current scale of the particle.
  55184. */
  55185. this.scale = new BABYLON.Vector2(1, 1);
  55186. /**
  55187. * The current angle of the particle.
  55188. */
  55189. this.angle = 0;
  55190. /**
  55191. * Defines how fast is the angle changing.
  55192. */
  55193. this.angularSpeed = 0;
  55194. /**
  55195. * Defines the cell index used by the particle to be rendered from a sprite.
  55196. */
  55197. this.cellIndex = 0;
  55198. /** @hidden */
  55199. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55200. /** @hidden */
  55201. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55202. /** @hidden */
  55203. this._currentSize1 = 0;
  55204. /** @hidden */
  55205. this._currentSize2 = 0;
  55206. /** @hidden */
  55207. this._currentAngularSpeed1 = 0;
  55208. /** @hidden */
  55209. this._currentAngularSpeed2 = 0;
  55210. /** @hidden */
  55211. this._currentVelocity1 = 0;
  55212. /** @hidden */
  55213. this._currentVelocity2 = 0;
  55214. /** @hidden */
  55215. this._currentLimitVelocity1 = 0;
  55216. /** @hidden */
  55217. this._currentLimitVelocity2 = 0;
  55218. if (!this.particleSystem.isAnimationSheetEnabled) {
  55219. return;
  55220. }
  55221. this.updateCellInfoFromSystem();
  55222. }
  55223. Particle.prototype.updateCellInfoFromSystem = function () {
  55224. this.cellIndex = this.particleSystem.startSpriteCellID;
  55225. };
  55226. /**
  55227. * Defines how the sprite cell index is updated for the particle
  55228. */
  55229. Particle.prototype.updateCellIndex = function () {
  55230. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55231. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55232. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55233. };
  55234. /**
  55235. * Copy the properties of particle to another one.
  55236. * @param other the particle to copy the information to.
  55237. */
  55238. Particle.prototype.copyTo = function (other) {
  55239. other.position.copyFrom(this.position);
  55240. if (this._initialDirection) {
  55241. if (other._initialDirection) {
  55242. other._initialDirection.copyFrom(this._initialDirection);
  55243. }
  55244. else {
  55245. other._initialDirection = this._initialDirection.clone();
  55246. }
  55247. }
  55248. else {
  55249. other._initialDirection = null;
  55250. }
  55251. other.direction.copyFrom(this.direction);
  55252. other.color.copyFrom(this.color);
  55253. other.colorStep.copyFrom(this.colorStep);
  55254. other.lifeTime = this.lifeTime;
  55255. other.age = this.age;
  55256. other.size = this.size;
  55257. other.scale.copyFrom(this.scale);
  55258. other.angle = this.angle;
  55259. other.angularSpeed = this.angularSpeed;
  55260. other.particleSystem = this.particleSystem;
  55261. other.cellIndex = this.cellIndex;
  55262. if (this._currentColorGradient) {
  55263. other._currentColorGradient = this._currentColorGradient;
  55264. other._currentColor1.copyFrom(this._currentColor1);
  55265. other._currentColor2.copyFrom(this._currentColor2);
  55266. }
  55267. if (this._currentSizeGradient) {
  55268. other._currentSizeGradient = this._currentSizeGradient;
  55269. other._currentSize1 = this._currentSize1;
  55270. other._currentSize2 = this._currentSize2;
  55271. }
  55272. if (this._currentAngularSpeedGradient) {
  55273. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55274. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55275. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55276. }
  55277. if (this._currentVelocityGradient) {
  55278. other._currentVelocityGradient = this._currentVelocityGradient;
  55279. other._currentVelocity1 = this._currentVelocity1;
  55280. other._currentVelocity2 = this._currentVelocity2;
  55281. }
  55282. if (this._currentLimitVelocityGradient) {
  55283. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55284. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55285. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55286. }
  55287. if (this.particleSystem.isAnimationSheetEnabled) {
  55288. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55289. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55290. }
  55291. };
  55292. return Particle;
  55293. }());
  55294. BABYLON.Particle = Particle;
  55295. })(BABYLON || (BABYLON = {}));
  55296. //# sourceMappingURL=babylon.particle.js.map
  55297. var BABYLON;
  55298. (function (BABYLON) {
  55299. /**
  55300. * This represents the base class for particle system in Babylon.
  55301. * 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.
  55302. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55303. * @example https://doc.babylonjs.com/babylon101/particles
  55304. */
  55305. var BaseParticleSystem = /** @class */ (function () {
  55306. /**
  55307. * Instantiates a particle system.
  55308. * 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.
  55309. * @param name The name of the particle system
  55310. */
  55311. function BaseParticleSystem(name) {
  55312. /**
  55313. * List of animations used by the particle system.
  55314. */
  55315. this.animations = [];
  55316. /**
  55317. * The rendering group used by the Particle system to chose when to render.
  55318. */
  55319. this.renderingGroupId = 0;
  55320. /**
  55321. * The emitter represents the Mesh or position we are attaching the particle system to.
  55322. */
  55323. this.emitter = null;
  55324. /**
  55325. * The maximum number of particles to emit per frame
  55326. */
  55327. this.emitRate = 10;
  55328. /**
  55329. * If you want to launch only a few particles at once, that can be done, as well.
  55330. */
  55331. this.manualEmitCount = -1;
  55332. /**
  55333. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55334. */
  55335. this.updateSpeed = 0.01;
  55336. /**
  55337. * The amount of time the particle system is running (depends of the overall update speed).
  55338. */
  55339. this.targetStopDuration = 0;
  55340. /**
  55341. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55342. */
  55343. this.disposeOnStop = false;
  55344. /**
  55345. * Minimum power of emitting particles.
  55346. */
  55347. this.minEmitPower = 1;
  55348. /**
  55349. * Maximum power of emitting particles.
  55350. */
  55351. this.maxEmitPower = 1;
  55352. /**
  55353. * Minimum life time of emitting particles.
  55354. */
  55355. this.minLifeTime = 1;
  55356. /**
  55357. * Maximum life time of emitting particles.
  55358. */
  55359. this.maxLifeTime = 1;
  55360. /**
  55361. * Minimum Size of emitting particles.
  55362. */
  55363. this.minSize = 1;
  55364. /**
  55365. * Maximum Size of emitting particles.
  55366. */
  55367. this.maxSize = 1;
  55368. /**
  55369. * Minimum scale of emitting particles on X axis.
  55370. */
  55371. this.minScaleX = 1;
  55372. /**
  55373. * Maximum scale of emitting particles on X axis.
  55374. */
  55375. this.maxScaleX = 1;
  55376. /**
  55377. * Minimum scale of emitting particles on Y axis.
  55378. */
  55379. this.minScaleY = 1;
  55380. /**
  55381. * Maximum scale of emitting particles on Y axis.
  55382. */
  55383. this.maxScaleY = 1;
  55384. /**
  55385. * Gets or sets the minimal initial rotation in radians.
  55386. */
  55387. this.minInitialRotation = 0;
  55388. /**
  55389. * Gets or sets the maximal initial rotation in radians.
  55390. */
  55391. this.maxInitialRotation = 0;
  55392. /**
  55393. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55394. */
  55395. this.minAngularSpeed = 0;
  55396. /**
  55397. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55398. */
  55399. this.maxAngularSpeed = 0;
  55400. /**
  55401. * The layer mask we are rendering the particles through.
  55402. */
  55403. this.layerMask = 0x0FFFFFFF;
  55404. /**
  55405. * This can help using your own shader to render the particle system.
  55406. * The according effect will be created
  55407. */
  55408. this.customShader = null;
  55409. /**
  55410. * By default particle system starts as soon as they are created. This prevents the
  55411. * automatic start to happen and let you decide when to start emitting particles.
  55412. */
  55413. this.preventAutoStart = false;
  55414. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55415. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55416. /**
  55417. * Callback triggered when the particle animation is ending.
  55418. */
  55419. this.onAnimationEnd = null;
  55420. /**
  55421. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55422. */
  55423. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55424. /**
  55425. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55426. * to override the particles.
  55427. */
  55428. this.forceDepthWrite = false;
  55429. /** 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 */
  55430. this.preWarmCycles = 0;
  55431. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55432. this.preWarmStepOffset = 1;
  55433. /**
  55434. * 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)
  55435. */
  55436. this.spriteCellChangeSpeed = 1;
  55437. /**
  55438. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55439. */
  55440. this.startSpriteCellID = 0;
  55441. /**
  55442. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55443. */
  55444. this.endSpriteCellID = 0;
  55445. /**
  55446. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55447. */
  55448. this.spriteCellWidth = 0;
  55449. /**
  55450. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55451. */
  55452. this.spriteCellHeight = 0;
  55453. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55454. this.translationPivot = new BABYLON.Vector2(0, 0);
  55455. /**
  55456. * You can use gravity if you want to give an orientation to your particles.
  55457. */
  55458. this.gravity = BABYLON.Vector3.Zero();
  55459. this._colorGradients = null;
  55460. this._sizeGradients = null;
  55461. this._lifeTimeGradients = null;
  55462. this._angularSpeedGradients = null;
  55463. this._velocityGradients = null;
  55464. this._limitVelocityGradients = null;
  55465. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55466. this.limitVelocityDamping = 0.4;
  55467. /**
  55468. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55469. */
  55470. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55471. /**
  55472. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55473. */
  55474. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55475. /**
  55476. * Color the particle will have at the end of its lifetime
  55477. */
  55478. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55479. /**
  55480. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55481. */
  55482. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55483. /**
  55484. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55485. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55486. */
  55487. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55488. this._isBillboardBased = true;
  55489. /**
  55490. * Local cache of defines for image processing.
  55491. */
  55492. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55493. this.id = name;
  55494. this.name = name;
  55495. }
  55496. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55497. /**
  55498. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55499. */
  55500. get: function () {
  55501. return this._isAnimationSheetEnabled;
  55502. },
  55503. set: function (value) {
  55504. if (this._isAnimationSheetEnabled == value) {
  55505. return;
  55506. }
  55507. this._isAnimationSheetEnabled = value;
  55508. this._reset();
  55509. },
  55510. enumerable: true,
  55511. configurable: true
  55512. });
  55513. /**
  55514. * Gets the current list of limit velocity gradients.
  55515. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55516. * @returns the list of limit velocity gradients
  55517. */
  55518. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55519. return this._limitVelocityGradients;
  55520. };
  55521. /**
  55522. * Gets the current list of color gradients.
  55523. * You must use addColorGradient and removeColorGradient to udpate this list
  55524. * @returns the list of color gradients
  55525. */
  55526. BaseParticleSystem.prototype.getColorGradients = function () {
  55527. return this._colorGradients;
  55528. };
  55529. /**
  55530. * Gets the current list of size gradients.
  55531. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55532. * @returns the list of size gradients
  55533. */
  55534. BaseParticleSystem.prototype.getSizeGradients = function () {
  55535. return this._sizeGradients;
  55536. };
  55537. /**
  55538. * Gets the current list of life time gradients.
  55539. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55540. * @returns the list of life time gradients
  55541. */
  55542. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55543. return this._lifeTimeGradients;
  55544. };
  55545. /**
  55546. * Gets the current list of angular speed gradients.
  55547. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55548. * @returns the list of angular speed gradients
  55549. */
  55550. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55551. return this._angularSpeedGradients;
  55552. };
  55553. /**
  55554. * Gets the current list of velocity gradients.
  55555. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55556. * @returns the list of velocity gradients
  55557. */
  55558. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55559. return this._velocityGradients;
  55560. };
  55561. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55562. /**
  55563. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55564. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55565. */
  55566. get: function () {
  55567. if (this.particleEmitterType.direction1) {
  55568. return this.particleEmitterType.direction1;
  55569. }
  55570. return BABYLON.Vector3.Zero();
  55571. },
  55572. set: function (value) {
  55573. if (this.particleEmitterType.direction1) {
  55574. this.particleEmitterType.direction1 = value;
  55575. }
  55576. },
  55577. enumerable: true,
  55578. configurable: true
  55579. });
  55580. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55581. /**
  55582. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55583. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55584. */
  55585. get: function () {
  55586. if (this.particleEmitterType.direction2) {
  55587. return this.particleEmitterType.direction2;
  55588. }
  55589. return BABYLON.Vector3.Zero();
  55590. },
  55591. set: function (value) {
  55592. if (this.particleEmitterType.direction2) {
  55593. this.particleEmitterType.direction2 = value;
  55594. }
  55595. },
  55596. enumerable: true,
  55597. configurable: true
  55598. });
  55599. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55600. /**
  55601. * 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.
  55602. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55603. */
  55604. get: function () {
  55605. if (this.particleEmitterType.minEmitBox) {
  55606. return this.particleEmitterType.minEmitBox;
  55607. }
  55608. return BABYLON.Vector3.Zero();
  55609. },
  55610. set: function (value) {
  55611. if (this.particleEmitterType.minEmitBox) {
  55612. this.particleEmitterType.minEmitBox = value;
  55613. }
  55614. },
  55615. enumerable: true,
  55616. configurable: true
  55617. });
  55618. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55619. /**
  55620. * 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.
  55621. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55622. */
  55623. get: function () {
  55624. if (this.particleEmitterType.maxEmitBox) {
  55625. return this.particleEmitterType.maxEmitBox;
  55626. }
  55627. return BABYLON.Vector3.Zero();
  55628. },
  55629. set: function (value) {
  55630. if (this.particleEmitterType.maxEmitBox) {
  55631. this.particleEmitterType.maxEmitBox = value;
  55632. }
  55633. },
  55634. enumerable: true,
  55635. configurable: true
  55636. });
  55637. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55638. /**
  55639. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55640. */
  55641. get: function () {
  55642. return this._isBillboardBased;
  55643. },
  55644. set: function (value) {
  55645. if (this._isBillboardBased === value) {
  55646. return;
  55647. }
  55648. this._isBillboardBased = value;
  55649. this._reset();
  55650. },
  55651. enumerable: true,
  55652. configurable: true
  55653. });
  55654. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55655. /**
  55656. * Gets the image processing configuration used either in this material.
  55657. */
  55658. get: function () {
  55659. return this._imageProcessingConfiguration;
  55660. },
  55661. /**
  55662. * Sets the Default image processing configuration used either in the this material.
  55663. *
  55664. * If sets to null, the scene one is in use.
  55665. */
  55666. set: function (value) {
  55667. this._attachImageProcessingConfiguration(value);
  55668. },
  55669. enumerable: true,
  55670. configurable: true
  55671. });
  55672. /**
  55673. * Attaches a new image processing configuration to the Standard Material.
  55674. * @param configuration
  55675. */
  55676. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55677. if (configuration === this._imageProcessingConfiguration) {
  55678. return;
  55679. }
  55680. // Pick the scene configuration if needed.
  55681. if (!configuration) {
  55682. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55683. }
  55684. else {
  55685. this._imageProcessingConfiguration = configuration;
  55686. }
  55687. };
  55688. /** @hidden */
  55689. BaseParticleSystem.prototype._reset = function () {
  55690. };
  55691. /**
  55692. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55693. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55694. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55695. * @returns the emitter
  55696. */
  55697. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55698. var particleEmitter = new BABYLON.PointParticleEmitter();
  55699. particleEmitter.direction1 = direction1;
  55700. particleEmitter.direction2 = direction2;
  55701. this.particleEmitterType = particleEmitter;
  55702. return particleEmitter;
  55703. };
  55704. /**
  55705. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55706. * @param radius The radius of the hemisphere to emit from
  55707. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55708. * @returns the emitter
  55709. */
  55710. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  55711. if (radius === void 0) { radius = 1; }
  55712. if (radiusRange === void 0) { radiusRange = 1; }
  55713. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  55714. this.particleEmitterType = particleEmitter;
  55715. return particleEmitter;
  55716. };
  55717. /**
  55718. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  55719. * @param radius The radius of the sphere to emit from
  55720. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55721. * @returns the emitter
  55722. */
  55723. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  55724. if (radius === void 0) { radius = 1; }
  55725. if (radiusRange === void 0) { radiusRange = 1; }
  55726. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  55727. this.particleEmitterType = particleEmitter;
  55728. return particleEmitter;
  55729. };
  55730. /**
  55731. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  55732. * @param radius The radius of the sphere to emit from
  55733. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55734. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55735. * @returns the emitter
  55736. */
  55737. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55738. if (radius === void 0) { radius = 1; }
  55739. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55740. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55741. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55742. this.particleEmitterType = particleEmitter;
  55743. return particleEmitter;
  55744. };
  55745. /**
  55746. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  55747. * @param radius The radius of the cone to emit from
  55748. * @param angle The base angle of the cone
  55749. * @returns the emitter
  55750. */
  55751. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55752. if (radius === void 0) { radius = 1; }
  55753. if (angle === void 0) { angle = Math.PI / 4; }
  55754. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55755. this.particleEmitterType = particleEmitter;
  55756. return particleEmitter;
  55757. };
  55758. /**
  55759. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55760. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55761. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55762. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55763. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55764. * @returns the emitter
  55765. */
  55766. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55767. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55768. this.particleEmitterType = particleEmitter;
  55769. this.direction1 = direction1;
  55770. this.direction2 = direction2;
  55771. this.minEmitBox = minEmitBox;
  55772. this.maxEmitBox = maxEmitBox;
  55773. return particleEmitter;
  55774. };
  55775. /**
  55776. * Source color is added to the destination color without alpha affecting the result.
  55777. */
  55778. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  55779. /**
  55780. * Blend current color and particle color using particle’s alpha.
  55781. */
  55782. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  55783. /**
  55784. * Add current color and particle color multiplied by particle’s alpha.
  55785. */
  55786. BaseParticleSystem.BLENDMODE_ADD = 2;
  55787. return BaseParticleSystem;
  55788. }());
  55789. BABYLON.BaseParticleSystem = BaseParticleSystem;
  55790. })(BABYLON || (BABYLON = {}));
  55791. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  55792. var BABYLON;
  55793. (function (BABYLON) {
  55794. /**
  55795. * This represents a particle system in Babylon.
  55796. * 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.
  55797. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55798. * @example https://doc.babylonjs.com/babylon101/particles
  55799. */
  55800. var ParticleSystem = /** @class */ (function (_super) {
  55801. __extends(ParticleSystem, _super);
  55802. /**
  55803. * Instantiates a particle system.
  55804. * 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.
  55805. * @param name The name of the particle system
  55806. * @param capacity The max number of particles alive at the same time
  55807. * @param scene The scene the particle system belongs to
  55808. * @param customEffect a custom effect used to change the way particles are rendered by default
  55809. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55810. * @param epsilon Offset used to render the particles
  55811. */
  55812. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55813. if (customEffect === void 0) { customEffect = null; }
  55814. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55815. if (epsilon === void 0) { epsilon = 0.01; }
  55816. var _this = _super.call(this, name) || this;
  55817. /**
  55818. * An event triggered when the system is disposed
  55819. */
  55820. _this.onDisposeObservable = new BABYLON.Observable();
  55821. _this._particles = new Array();
  55822. _this._stockParticles = new Array();
  55823. _this._newPartsExcess = 0;
  55824. _this._vertexBuffers = {};
  55825. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55826. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55827. _this._scaledDirection = BABYLON.Vector3.Zero();
  55828. _this._scaledGravity = BABYLON.Vector3.Zero();
  55829. _this._currentRenderId = -1;
  55830. _this._useInstancing = false;
  55831. _this._started = false;
  55832. _this._stopped = false;
  55833. _this._actualFrame = 0;
  55834. // start of sub system methods
  55835. /**
  55836. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55837. * Its lifetime will start back at 0.
  55838. */
  55839. _this.recycleParticle = function (particle) {
  55840. var lastParticle = _this._particles.pop();
  55841. if (lastParticle !== particle) {
  55842. lastParticle.copyTo(particle);
  55843. }
  55844. _this._stockParticles.push(lastParticle);
  55845. };
  55846. _this._createParticle = function () {
  55847. var particle;
  55848. if (_this._stockParticles.length !== 0) {
  55849. particle = _this._stockParticles.pop();
  55850. particle.age = 0;
  55851. particle._currentColorGradient = null;
  55852. particle.cellIndex = _this.startSpriteCellID;
  55853. }
  55854. else {
  55855. particle = new BABYLON.Particle(_this);
  55856. }
  55857. return particle;
  55858. };
  55859. _this._emitFromParticle = function (particle) {
  55860. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55861. return;
  55862. }
  55863. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55864. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55865. subSystem._rootParticleSystem = _this;
  55866. _this.activeSubSystems.push(subSystem);
  55867. subSystem.start();
  55868. };
  55869. _this._capacity = capacity;
  55870. _this._epsilon = epsilon;
  55871. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55872. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55873. // Setup the default processing configuration to the scene.
  55874. _this._attachImageProcessingConfiguration(null);
  55875. _this._customEffect = customEffect;
  55876. _this._scene.particleSystems.push(_this);
  55877. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  55878. _this._createIndexBuffer();
  55879. _this._createVertexBuffers();
  55880. // Default emitter type
  55881. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55882. _this.updateFunction = function (particles) {
  55883. var noiseTextureData = null;
  55884. var noiseTextureSize = null;
  55885. if (_this.noiseTexture) { // We need to get texture data back to CPU
  55886. noiseTextureData = (_this.noiseTexture.readPixels());
  55887. noiseTextureSize = _this.noiseTexture.getSize();
  55888. }
  55889. var _loop_1 = function () {
  55890. particle = particles[index];
  55891. particle.age += _this._scaledUpdateSpeed;
  55892. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55893. _this._emitFromParticle(particle);
  55894. _this.recycleParticle(particle);
  55895. index--;
  55896. return "continue";
  55897. }
  55898. else {
  55899. var ratio = particle.age / particle.lifeTime;
  55900. // Color
  55901. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55902. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55903. if (currentGradient !== particle._currentColorGradient) {
  55904. particle._currentColor1.copyFrom(particle._currentColor2);
  55905. nextGradient.getColorToRef(particle._currentColor2);
  55906. particle._currentColorGradient = currentGradient;
  55907. }
  55908. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55909. });
  55910. }
  55911. else {
  55912. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55913. particle.color.addInPlace(_this._scaledColorStep);
  55914. if (particle.color.a < 0) {
  55915. particle.color.a = 0;
  55916. }
  55917. }
  55918. // Angular speed
  55919. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55920. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55921. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55922. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55923. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55924. particle._currentAngularSpeedGradient = currentGradient;
  55925. }
  55926. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55927. });
  55928. }
  55929. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55930. // Direction
  55931. var directionScale_1 = _this._scaledUpdateSpeed;
  55932. /// Velocity
  55933. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55934. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55935. if (currentGradient !== particle._currentVelocityGradient) {
  55936. particle._currentVelocity1 = particle._currentVelocity2;
  55937. particle._currentVelocity2 = nextGradient.getFactor();
  55938. particle._currentVelocityGradient = currentGradient;
  55939. }
  55940. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55941. });
  55942. }
  55943. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55944. /// Limit velocity
  55945. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  55946. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  55947. if (currentGradient !== particle._currentLimitVelocityGradient) {
  55948. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  55949. particle._currentLimitVelocity2 = nextGradient.getFactor();
  55950. particle._currentLimitVelocityGradient = currentGradient;
  55951. }
  55952. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  55953. var currentVelocity = particle.direction.length();
  55954. if (currentVelocity > limitVelocity) {
  55955. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  55956. }
  55957. });
  55958. }
  55959. particle.position.addInPlace(_this._scaledDirection);
  55960. // Noise
  55961. if (noiseTextureData && noiseTextureSize) {
  55962. var localPosition = BABYLON.Tmp.Vector3[0];
  55963. var emitterPosition = BABYLON.Tmp.Vector3[1];
  55964. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  55965. particle.position.subtractToRef(emitterPosition, localPosition);
  55966. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55967. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55968. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55969. var force = BABYLON.Tmp.Vector3[0];
  55970. var scaledForce = BABYLON.Tmp.Vector3[1];
  55971. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  55972. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  55973. particle.direction.addInPlace(scaledForce);
  55974. }
  55975. // Gravity
  55976. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55977. particle.direction.addInPlace(_this._scaledGravity);
  55978. // Size
  55979. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55980. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55981. if (currentGradient !== particle._currentSizeGradient) {
  55982. particle._currentSize1 = particle._currentSize2;
  55983. particle._currentSize2 = nextGradient.getFactor();
  55984. particle._currentSizeGradient = currentGradient;
  55985. }
  55986. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55987. });
  55988. }
  55989. if (_this._isAnimationSheetEnabled) {
  55990. particle.updateCellIndex();
  55991. }
  55992. }
  55993. };
  55994. var particle;
  55995. for (var index = 0; index < particles.length; index++) {
  55996. _loop_1();
  55997. }
  55998. };
  55999. return _this;
  56000. }
  56001. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56002. /**
  56003. * Sets a callback that will be triggered when the system is disposed
  56004. */
  56005. set: function (callback) {
  56006. if (this._onDisposeObserver) {
  56007. this.onDisposeObservable.remove(this._onDisposeObserver);
  56008. }
  56009. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56010. },
  56011. enumerable: true,
  56012. configurable: true
  56013. });
  56014. /**
  56015. * Get hosting scene
  56016. * @returns the scene
  56017. */
  56018. ParticleSystem.prototype.getScene = function () {
  56019. return this._scene;
  56020. };
  56021. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56022. //end of Sub-emitter
  56023. /**
  56024. * Gets the current list of active particles
  56025. */
  56026. get: function () {
  56027. return this._particles;
  56028. },
  56029. enumerable: true,
  56030. configurable: true
  56031. });
  56032. /**
  56033. * Returns the string "ParticleSystem"
  56034. * @returns a string containing the class name
  56035. */
  56036. ParticleSystem.prototype.getClassName = function () {
  56037. return "ParticleSystem";
  56038. };
  56039. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56040. var newGradient = new BABYLON.FactorGradient();
  56041. newGradient.gradient = gradient;
  56042. newGradient.factor1 = factor;
  56043. newGradient.factor2 = factor2;
  56044. factorGradients.push(newGradient);
  56045. factorGradients.sort(function (a, b) {
  56046. if (a.gradient < b.gradient) {
  56047. return -1;
  56048. }
  56049. else if (a.gradient > b.gradient) {
  56050. return 1;
  56051. }
  56052. return 0;
  56053. });
  56054. };
  56055. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56056. if (!factorGradients) {
  56057. return;
  56058. }
  56059. var index = 0;
  56060. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56061. var factorGradient = factorGradients_1[_i];
  56062. if (factorGradient.gradient === gradient) {
  56063. factorGradients.splice(index, 1);
  56064. break;
  56065. }
  56066. index++;
  56067. }
  56068. };
  56069. /**
  56070. * Adds a new life time gradient
  56071. * @param gradient defines the gradient to use (between 0 and 1)
  56072. * @param factor defines the life time factor to affect to the specified gradient
  56073. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56074. * @returns the current particle system
  56075. */
  56076. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56077. if (!this._lifeTimeGradients) {
  56078. this._lifeTimeGradients = [];
  56079. }
  56080. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56081. return this;
  56082. };
  56083. /**
  56084. * Remove a specific life time gradient
  56085. * @param gradient defines the gradient to remove
  56086. * @returns the current particle system
  56087. */
  56088. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56089. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56090. return this;
  56091. };
  56092. /**
  56093. * Adds a new size gradient
  56094. * @param gradient defines the gradient to use (between 0 and 1)
  56095. * @param factor defines the size factor to affect to the specified gradient
  56096. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56097. * @returns the current particle system
  56098. */
  56099. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56100. if (!this._sizeGradients) {
  56101. this._sizeGradients = [];
  56102. }
  56103. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56104. return this;
  56105. };
  56106. /**
  56107. * Remove a specific size gradient
  56108. * @param gradient defines the gradient to remove
  56109. * @returns the current particle system
  56110. */
  56111. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56112. this._removeFactorGradient(this._sizeGradients, gradient);
  56113. return this;
  56114. };
  56115. /**
  56116. * Adds a new angular speed gradient
  56117. * @param gradient defines the gradient to use (between 0 and 1)
  56118. * @param factor defines the angular speed to affect to the specified gradient
  56119. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56120. * @returns the current particle system
  56121. */
  56122. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56123. if (!this._angularSpeedGradients) {
  56124. this._angularSpeedGradients = [];
  56125. }
  56126. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56127. return this;
  56128. };
  56129. /**
  56130. * Remove a specific angular speed gradient
  56131. * @param gradient defines the gradient to remove
  56132. * @returns the current particle system
  56133. */
  56134. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56135. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56136. return this;
  56137. };
  56138. /**
  56139. * Adds a new velocity gradient
  56140. * @param gradient defines the gradient to use (between 0 and 1)
  56141. * @param factor defines the velocity to affect to the specified gradient
  56142. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56143. * @returns the current particle system
  56144. */
  56145. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56146. if (!this._velocityGradients) {
  56147. this._velocityGradients = [];
  56148. }
  56149. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56150. return this;
  56151. };
  56152. /**
  56153. * Remove a specific velocity gradient
  56154. * @param gradient defines the gradient to remove
  56155. * @returns the current particle system
  56156. */
  56157. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56158. this._removeFactorGradient(this._velocityGradients, gradient);
  56159. return this;
  56160. };
  56161. /**
  56162. * Adds a new limit velocity gradient
  56163. * @param gradient defines the gradient to use (between 0 and 1)
  56164. * @param factor defines the limit velocity value to affect to the specified gradient
  56165. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56166. * @returns the current particle system
  56167. */
  56168. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56169. if (!this._limitVelocityGradients) {
  56170. this._limitVelocityGradients = [];
  56171. }
  56172. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56173. return this;
  56174. };
  56175. /**
  56176. * Remove a specific limit velocity gradient
  56177. * @param gradient defines the gradient to remove
  56178. * @returns the current particle system
  56179. */
  56180. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56181. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56182. return this;
  56183. };
  56184. /**
  56185. * Adds a new color gradient
  56186. * @param gradient defines the gradient to use (between 0 and 1)
  56187. * @param color defines the color to affect to the specified gradient
  56188. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56189. */
  56190. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56191. if (!this._colorGradients) {
  56192. this._colorGradients = [];
  56193. }
  56194. var colorGradient = new BABYLON.ColorGradient();
  56195. colorGradient.gradient = gradient;
  56196. colorGradient.color1 = color;
  56197. colorGradient.color2 = color2;
  56198. this._colorGradients.push(colorGradient);
  56199. this._colorGradients.sort(function (a, b) {
  56200. if (a.gradient < b.gradient) {
  56201. return -1;
  56202. }
  56203. else if (a.gradient > b.gradient) {
  56204. return 1;
  56205. }
  56206. return 0;
  56207. });
  56208. return this;
  56209. };
  56210. /**
  56211. * Remove a specific color gradient
  56212. * @param gradient defines the gradient to remove
  56213. */
  56214. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56215. if (!this._colorGradients) {
  56216. return this;
  56217. }
  56218. var index = 0;
  56219. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56220. var colorGradient = _a[_i];
  56221. if (colorGradient.gradient === gradient) {
  56222. this._colorGradients.splice(index, 1);
  56223. break;
  56224. }
  56225. index++;
  56226. }
  56227. return this;
  56228. };
  56229. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56230. u = Math.abs(u) * 0.5 + 0.5;
  56231. v = Math.abs(v) * 0.5 + 0.5;
  56232. var wrappedU = ((u * width) % width) | 0;
  56233. var wrappedV = ((v * height) % height) | 0;
  56234. var position = (wrappedU + wrappedV * width) * 4;
  56235. return pixels[position] / 255;
  56236. };
  56237. ParticleSystem.prototype._reset = function () {
  56238. this._resetEffect();
  56239. };
  56240. ParticleSystem.prototype._resetEffect = function () {
  56241. if (this._vertexBuffer) {
  56242. this._vertexBuffer.dispose();
  56243. this._vertexBuffer = null;
  56244. }
  56245. if (this._spriteBuffer) {
  56246. this._spriteBuffer.dispose();
  56247. this._spriteBuffer = null;
  56248. }
  56249. this._createVertexBuffers();
  56250. };
  56251. ParticleSystem.prototype._createVertexBuffers = function () {
  56252. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56253. if (this._isAnimationSheetEnabled) {
  56254. this._vertexBufferSize += 1;
  56255. }
  56256. if (!this._isBillboardBased) {
  56257. this._vertexBufferSize += 3;
  56258. }
  56259. var engine = this._scene.getEngine();
  56260. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56261. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56262. var dataOffset = 0;
  56263. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56264. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56265. dataOffset += 3;
  56266. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56267. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56268. dataOffset += 4;
  56269. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56270. this._vertexBuffers["angle"] = options;
  56271. dataOffset += 1;
  56272. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56273. this._vertexBuffers["size"] = size;
  56274. dataOffset += 2;
  56275. if (this._isAnimationSheetEnabled) {
  56276. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56277. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56278. dataOffset += 1;
  56279. }
  56280. if (!this._isBillboardBased) {
  56281. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56282. this._vertexBuffers["direction"] = directionBuffer;
  56283. dataOffset += 3;
  56284. }
  56285. var offsets;
  56286. if (this._useInstancing) {
  56287. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56288. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56289. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56290. }
  56291. else {
  56292. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56293. dataOffset += 2;
  56294. }
  56295. this._vertexBuffers["offset"] = offsets;
  56296. };
  56297. ParticleSystem.prototype._createIndexBuffer = function () {
  56298. if (this._useInstancing) {
  56299. return;
  56300. }
  56301. var indices = [];
  56302. var index = 0;
  56303. for (var count = 0; count < this._capacity; count++) {
  56304. indices.push(index);
  56305. indices.push(index + 1);
  56306. indices.push(index + 2);
  56307. indices.push(index);
  56308. indices.push(index + 2);
  56309. indices.push(index + 3);
  56310. index += 4;
  56311. }
  56312. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56313. };
  56314. /**
  56315. * Gets the maximum number of particles active at the same time.
  56316. * @returns The max number of active particles.
  56317. */
  56318. ParticleSystem.prototype.getCapacity = function () {
  56319. return this._capacity;
  56320. };
  56321. /**
  56322. * Gets whether there are still active particles in the system.
  56323. * @returns True if it is alive, otherwise false.
  56324. */
  56325. ParticleSystem.prototype.isAlive = function () {
  56326. return this._alive;
  56327. };
  56328. /**
  56329. * Gets whether the system has been started.
  56330. * @returns True if it has been started, otherwise false.
  56331. */
  56332. ParticleSystem.prototype.isStarted = function () {
  56333. return this._started;
  56334. };
  56335. /**
  56336. * Starts the particle system and begins to emit
  56337. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56338. */
  56339. ParticleSystem.prototype.start = function (delay) {
  56340. var _this = this;
  56341. if (delay === void 0) { delay = 0; }
  56342. if (delay) {
  56343. setTimeout(function () {
  56344. _this.start(0);
  56345. }, delay);
  56346. return;
  56347. }
  56348. this._started = true;
  56349. this._stopped = false;
  56350. this._actualFrame = 0;
  56351. if (this.subEmitters && this.subEmitters.length != 0) {
  56352. this.activeSubSystems = new Array();
  56353. }
  56354. if (this.preWarmCycles) {
  56355. for (var index = 0; index < this.preWarmCycles; index++) {
  56356. this.animate(true);
  56357. }
  56358. }
  56359. };
  56360. /**
  56361. * Stops the particle system.
  56362. * @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.
  56363. */
  56364. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56365. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56366. this._stopped = true;
  56367. if (stopSubEmitters) {
  56368. this._stopSubEmitters();
  56369. }
  56370. };
  56371. // animation sheet
  56372. /**
  56373. * Remove all active particles
  56374. */
  56375. ParticleSystem.prototype.reset = function () {
  56376. this._stockParticles = [];
  56377. this._particles = [];
  56378. };
  56379. /**
  56380. * @hidden (for internal use only)
  56381. */
  56382. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56383. var offset = index * this._vertexBufferSize;
  56384. this._vertexData[offset++] = particle.position.x;
  56385. this._vertexData[offset++] = particle.position.y;
  56386. this._vertexData[offset++] = particle.position.z;
  56387. this._vertexData[offset++] = particle.color.r;
  56388. this._vertexData[offset++] = particle.color.g;
  56389. this._vertexData[offset++] = particle.color.b;
  56390. this._vertexData[offset++] = particle.color.a;
  56391. this._vertexData[offset++] = particle.angle;
  56392. this._vertexData[offset++] = particle.scale.x * particle.size;
  56393. this._vertexData[offset++] = particle.scale.y * particle.size;
  56394. if (this._isAnimationSheetEnabled) {
  56395. this._vertexData[offset++] = particle.cellIndex;
  56396. }
  56397. if (!this._isBillboardBased) {
  56398. if (particle._initialDirection) {
  56399. this._vertexData[offset++] = particle._initialDirection.x;
  56400. this._vertexData[offset++] = particle._initialDirection.y;
  56401. this._vertexData[offset++] = particle._initialDirection.z;
  56402. }
  56403. else {
  56404. this._vertexData[offset++] = particle.direction.x;
  56405. this._vertexData[offset++] = particle.direction.y;
  56406. this._vertexData[offset++] = particle.direction.z;
  56407. }
  56408. }
  56409. if (!this._useInstancing) {
  56410. if (this._isAnimationSheetEnabled) {
  56411. if (offsetX === 0)
  56412. offsetX = this._epsilon;
  56413. else if (offsetX === 1)
  56414. offsetX = 1 - this._epsilon;
  56415. if (offsetY === 0)
  56416. offsetY = this._epsilon;
  56417. else if (offsetY === 1)
  56418. offsetY = 1 - this._epsilon;
  56419. }
  56420. this._vertexData[offset++] = offsetX;
  56421. this._vertexData[offset++] = offsetY;
  56422. }
  56423. };
  56424. ParticleSystem.prototype._stopSubEmitters = function () {
  56425. if (!this.activeSubSystems) {
  56426. return;
  56427. }
  56428. this.activeSubSystems.forEach(function (subSystem) {
  56429. subSystem.stop(true);
  56430. });
  56431. this.activeSubSystems = new Array();
  56432. };
  56433. ParticleSystem.prototype._removeFromRoot = function () {
  56434. if (!this._rootParticleSystem) {
  56435. return;
  56436. }
  56437. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56438. if (index !== -1) {
  56439. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56440. }
  56441. };
  56442. // End of sub system methods
  56443. ParticleSystem.prototype._update = function (newParticles) {
  56444. // Update current
  56445. this._alive = this._particles.length > 0;
  56446. if (this.emitter.position) {
  56447. var emitterMesh = this.emitter;
  56448. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56449. }
  56450. else {
  56451. var emitterPosition = this.emitter;
  56452. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56453. }
  56454. this.updateFunction(this._particles);
  56455. // Add new ones
  56456. var particle;
  56457. var _loop_2 = function () {
  56458. if (this_1._particles.length === this_1._capacity) {
  56459. return "break";
  56460. }
  56461. particle = this_1._createParticle();
  56462. this_1._particles.push(particle);
  56463. // Emitter
  56464. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56465. if (this_1.startPositionFunction) {
  56466. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56467. }
  56468. else {
  56469. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56470. }
  56471. if (this_1.startDirectionFunction) {
  56472. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56473. }
  56474. else {
  56475. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56476. }
  56477. if (emitPower === 0) {
  56478. if (!particle._initialDirection) {
  56479. particle._initialDirection = particle.direction.clone();
  56480. }
  56481. else {
  56482. particle._initialDirection.copyFrom(particle.direction);
  56483. }
  56484. }
  56485. else {
  56486. particle._initialDirection = null;
  56487. }
  56488. particle.direction.scaleInPlace(emitPower);
  56489. // Life time
  56490. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56491. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56492. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56493. var factorGradient1 = currentGradient;
  56494. var factorGradient2 = nextGradient;
  56495. var lifeTime1 = factorGradient1.getFactor();
  56496. var lifeTime2 = factorGradient2.getFactor();
  56497. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56498. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56499. });
  56500. }
  56501. else {
  56502. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56503. }
  56504. // Size
  56505. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56506. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56507. }
  56508. else {
  56509. particle._currentSizeGradient = this_1._sizeGradients[0];
  56510. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56511. particle.size = particle._currentSize1;
  56512. if (this_1._sizeGradients.length > 1) {
  56513. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56514. }
  56515. else {
  56516. particle._currentSize2 = particle._currentSize1;
  56517. }
  56518. }
  56519. // Size and scale
  56520. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56521. // Angle
  56522. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56523. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56524. }
  56525. else {
  56526. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56527. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56528. particle._currentAngularSpeed1 = particle.angularSpeed;
  56529. if (this_1._angularSpeedGradients.length > 1) {
  56530. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56531. }
  56532. else {
  56533. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56534. }
  56535. }
  56536. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56537. // Velocity
  56538. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56539. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56540. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56541. if (this_1._velocityGradients.length > 1) {
  56542. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56543. }
  56544. else {
  56545. particle._currentVelocity2 = particle._currentVelocity1;
  56546. }
  56547. }
  56548. // Limit velocity
  56549. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  56550. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  56551. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  56552. if (this_1._limitVelocityGradients.length > 1) {
  56553. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  56554. }
  56555. else {
  56556. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  56557. }
  56558. }
  56559. // Color
  56560. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  56561. step = BABYLON.Scalar.RandomRange(0, 1.0);
  56562. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  56563. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  56564. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56565. }
  56566. else {
  56567. particle._currentColorGradient = this_1._colorGradients[0];
  56568. particle._currentColorGradient.getColorToRef(particle.color);
  56569. particle._currentColor1.copyFrom(particle.color);
  56570. if (this_1._colorGradients.length > 1) {
  56571. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  56572. }
  56573. else {
  56574. particle._currentColor2.copyFrom(particle.color);
  56575. }
  56576. }
  56577. // Sheet
  56578. if (this_1._isAnimationSheetEnabled) {
  56579. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56580. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56581. }
  56582. };
  56583. var this_1 = this, step;
  56584. for (var index = 0; index < newParticles; index++) {
  56585. var state_1 = _loop_2();
  56586. if (state_1 === "break")
  56587. break;
  56588. }
  56589. };
  56590. /** @hidden */
  56591. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  56592. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56593. if (isBillboardBased === void 0) { isBillboardBased = false; }
  56594. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  56595. if (isAnimationSheetEnabled) {
  56596. attributeNamesOrOptions.push("cellIndex");
  56597. }
  56598. if (!isBillboardBased) {
  56599. attributeNamesOrOptions.push("direction");
  56600. }
  56601. return attributeNamesOrOptions;
  56602. };
  56603. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56604. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56605. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  56606. if (isAnimationSheetEnabled) {
  56607. effectCreationOption.push("particlesInfos");
  56608. }
  56609. return effectCreationOption;
  56610. };
  56611. ParticleSystem.prototype._getEffect = function () {
  56612. if (this._customEffect) {
  56613. return this._customEffect;
  56614. }
  56615. ;
  56616. var defines = [];
  56617. if (this._scene.clipPlane) {
  56618. defines.push("#define CLIPPLANE");
  56619. }
  56620. if (this._isAnimationSheetEnabled) {
  56621. defines.push("#define ANIMATESHEET");
  56622. }
  56623. if (this._isBillboardBased) {
  56624. defines.push("#define BILLBOARD");
  56625. switch (this.billboardMode) {
  56626. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56627. defines.push("#define BILLBOARDY");
  56628. break;
  56629. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56630. default:
  56631. break;
  56632. }
  56633. }
  56634. if (this._imageProcessingConfiguration) {
  56635. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  56636. defines.push(this._imageProcessingConfigurationDefines.toString());
  56637. }
  56638. // Effect
  56639. var join = defines.join("\n");
  56640. if (this._cachedDefines !== join) {
  56641. this._cachedDefines = join;
  56642. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56643. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56644. var samplers = ["diffuseSampler"];
  56645. if (BABYLON.ImageProcessingConfiguration) {
  56646. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  56647. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  56648. }
  56649. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56650. }
  56651. return this._effect;
  56652. };
  56653. /**
  56654. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56655. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56656. */
  56657. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56658. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56659. if (!this._started)
  56660. return;
  56661. if (!preWarmOnly) {
  56662. var effect = this._getEffect();
  56663. // Check
  56664. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56665. return;
  56666. if (this._currentRenderId === this._scene.getRenderId()) {
  56667. return;
  56668. }
  56669. this._currentRenderId = this._scene.getRenderId();
  56670. }
  56671. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56672. // determine the number of particles we need to create
  56673. var newParticles;
  56674. if (this.manualEmitCount > -1) {
  56675. newParticles = this.manualEmitCount;
  56676. this._newPartsExcess = 0;
  56677. this.manualEmitCount = 0;
  56678. }
  56679. else {
  56680. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56681. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56682. }
  56683. if (this._newPartsExcess > 1.0) {
  56684. newParticles += this._newPartsExcess >> 0;
  56685. this._newPartsExcess -= this._newPartsExcess >> 0;
  56686. }
  56687. this._alive = false;
  56688. if (!this._stopped) {
  56689. this._actualFrame += this._scaledUpdateSpeed;
  56690. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56691. this.stop();
  56692. }
  56693. else {
  56694. newParticles = 0;
  56695. }
  56696. this._update(newParticles);
  56697. // Stopped?
  56698. if (this._stopped) {
  56699. if (!this._alive) {
  56700. this._started = false;
  56701. if (this.onAnimationEnd) {
  56702. this.onAnimationEnd();
  56703. }
  56704. if (this.disposeOnStop) {
  56705. this._scene._toBeDisposed.push(this);
  56706. }
  56707. }
  56708. }
  56709. if (!preWarmOnly) {
  56710. // Update VBO
  56711. var offset = 0;
  56712. for (var index = 0; index < this._particles.length; index++) {
  56713. var particle = this._particles[index];
  56714. this._appendParticleVertices(offset, particle);
  56715. offset += this._useInstancing ? 1 : 4;
  56716. }
  56717. if (this._vertexBuffer) {
  56718. this._vertexBuffer.update(this._vertexData);
  56719. }
  56720. }
  56721. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56722. this.stop();
  56723. }
  56724. };
  56725. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56726. this._appendParticleVertex(offset++, particle, 0, 0);
  56727. if (!this._useInstancing) {
  56728. this._appendParticleVertex(offset++, particle, 1, 0);
  56729. this._appendParticleVertex(offset++, particle, 1, 1);
  56730. this._appendParticleVertex(offset++, particle, 0, 1);
  56731. }
  56732. };
  56733. /**
  56734. * Rebuilds the particle system.
  56735. */
  56736. ParticleSystem.prototype.rebuild = function () {
  56737. this._createIndexBuffer();
  56738. if (this._vertexBuffer) {
  56739. this._vertexBuffer._rebuild();
  56740. }
  56741. };
  56742. /**
  56743. * Is this system ready to be used/rendered
  56744. * @return true if the system is ready
  56745. */
  56746. ParticleSystem.prototype.isReady = function () {
  56747. var effect = this._getEffect();
  56748. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56749. return false;
  56750. }
  56751. return true;
  56752. };
  56753. /**
  56754. * Renders the particle system in its current state.
  56755. * @returns the current number of particles
  56756. */
  56757. ParticleSystem.prototype.render = function () {
  56758. var effect = this._getEffect();
  56759. // Check
  56760. if (!this.isReady() || !this._particles.length) {
  56761. return 0;
  56762. }
  56763. var engine = this._scene.getEngine();
  56764. // Render
  56765. engine.enableEffect(effect);
  56766. engine.setState(false);
  56767. var viewMatrix = this._scene.getViewMatrix();
  56768. effect.setTexture("diffuseSampler", this.particleTexture);
  56769. effect.setMatrix("view", viewMatrix);
  56770. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56771. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56772. var baseSize = this.particleTexture.getBaseSize();
  56773. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56774. }
  56775. effect.setVector2("translationPivot", this.translationPivot);
  56776. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56777. if (this._isBillboardBased) {
  56778. var camera = this._scene.activeCamera;
  56779. effect.setVector3("eyePosition", camera.globalPosition);
  56780. }
  56781. if (this._scene.clipPlane) {
  56782. var clipPlane = this._scene.clipPlane;
  56783. var invView = viewMatrix.clone();
  56784. invView.invert();
  56785. effect.setMatrix("invView", invView);
  56786. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56787. }
  56788. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56789. // image processing
  56790. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  56791. this._imageProcessingConfiguration.bind(effect);
  56792. }
  56793. // Draw order
  56794. switch (this.blendMode) {
  56795. case ParticleSystem.BLENDMODE_ADD:
  56796. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56797. break;
  56798. case ParticleSystem.BLENDMODE_ONEONE:
  56799. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56800. break;
  56801. case ParticleSystem.BLENDMODE_STANDARD:
  56802. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56803. break;
  56804. }
  56805. if (this.forceDepthWrite) {
  56806. engine.setDepthWrite(true);
  56807. }
  56808. if (this._useInstancing) {
  56809. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56810. engine.unbindInstanceAttributes();
  56811. }
  56812. else {
  56813. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56814. }
  56815. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56816. return this._particles.length;
  56817. };
  56818. /**
  56819. * Disposes the particle system and free the associated resources
  56820. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56821. */
  56822. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56823. if (disposeTexture === void 0) { disposeTexture = true; }
  56824. if (this._vertexBuffer) {
  56825. this._vertexBuffer.dispose();
  56826. this._vertexBuffer = null;
  56827. }
  56828. if (this._spriteBuffer) {
  56829. this._spriteBuffer.dispose();
  56830. this._spriteBuffer = null;
  56831. }
  56832. if (this._indexBuffer) {
  56833. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56834. this._indexBuffer = null;
  56835. }
  56836. if (disposeTexture && this.particleTexture) {
  56837. this.particleTexture.dispose();
  56838. this.particleTexture = null;
  56839. }
  56840. if (disposeTexture && this.noiseTexture) {
  56841. this.noiseTexture.dispose();
  56842. this.noiseTexture = null;
  56843. }
  56844. this._removeFromRoot();
  56845. // Remove from scene
  56846. var index = this._scene.particleSystems.indexOf(this);
  56847. if (index > -1) {
  56848. this._scene.particleSystems.splice(index, 1);
  56849. }
  56850. // Callback
  56851. this.onDisposeObservable.notifyObservers(this);
  56852. this.onDisposeObservable.clear();
  56853. };
  56854. // Clone
  56855. /**
  56856. * Clones the particle system.
  56857. * @param name The name of the cloned object
  56858. * @param newEmitter The new emitter to use
  56859. * @returns the cloned particle system
  56860. */
  56861. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56862. var custom = null;
  56863. var program = null;
  56864. if (this.customShader != null) {
  56865. program = this.customShader;
  56866. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56867. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56868. }
  56869. else if (this._customEffect) {
  56870. custom = this._customEffect;
  56871. }
  56872. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56873. result.customShader = program;
  56874. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56875. if (newEmitter === undefined) {
  56876. newEmitter = this.emitter;
  56877. }
  56878. result.emitter = newEmitter;
  56879. if (this.particleTexture) {
  56880. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56881. }
  56882. if (!this.preventAutoStart) {
  56883. result.start();
  56884. }
  56885. return result;
  56886. };
  56887. /**
  56888. * Serializes the particle system to a JSON object.
  56889. * @returns the JSON object
  56890. */
  56891. ParticleSystem.prototype.serialize = function () {
  56892. var serializationObject = {};
  56893. ParticleSystem._Serialize(serializationObject, this);
  56894. serializationObject.textureMask = this.textureMask.asArray();
  56895. serializationObject.customShader = this.customShader;
  56896. serializationObject.preventAutoStart = this.preventAutoStart;
  56897. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56898. return serializationObject;
  56899. };
  56900. /** @hidden */
  56901. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56902. serializationObject.name = particleSystem.name;
  56903. serializationObject.id = particleSystem.id;
  56904. serializationObject.capacity = particleSystem.getCapacity();
  56905. // Emitter
  56906. if (particleSystem.emitter.position) {
  56907. var emitterMesh = particleSystem.emitter;
  56908. serializationObject.emitterId = emitterMesh.id;
  56909. }
  56910. else {
  56911. var emitterPosition = particleSystem.emitter;
  56912. serializationObject.emitter = emitterPosition.asArray();
  56913. }
  56914. // Emitter
  56915. if (particleSystem.particleEmitterType) {
  56916. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56917. }
  56918. if (particleSystem.particleTexture) {
  56919. serializationObject.textureName = particleSystem.particleTexture.name;
  56920. }
  56921. // Animations
  56922. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56923. // Particle system
  56924. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56925. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56926. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56927. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56928. serializationObject.minSize = particleSystem.minSize;
  56929. serializationObject.maxSize = particleSystem.maxSize;
  56930. serializationObject.minScaleX = particleSystem.minScaleX;
  56931. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56932. serializationObject.minScaleY = particleSystem.minScaleY;
  56933. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56934. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56935. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56936. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56937. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56938. serializationObject.emitRate = particleSystem.emitRate;
  56939. serializationObject.gravity = particleSystem.gravity.asArray();
  56940. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  56941. serializationObject.color1 = particleSystem.color1.asArray();
  56942. serializationObject.color2 = particleSystem.color2.asArray();
  56943. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56944. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56945. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56946. serializationObject.blendMode = particleSystem.blendMode;
  56947. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56948. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56949. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56950. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56951. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56952. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56953. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56954. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56955. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56956. var colorGradients = particleSystem.getColorGradients();
  56957. if (colorGradients) {
  56958. serializationObject.colorGradients = [];
  56959. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56960. var colorGradient = colorGradients_1[_i];
  56961. var serializedGradient = {
  56962. gradient: colorGradient.gradient,
  56963. color1: colorGradient.color1.asArray()
  56964. };
  56965. if (colorGradient.color2) {
  56966. serializedGradient.color2 = colorGradient.color2.asArray();
  56967. }
  56968. serializationObject.colorGradients.push(serializedGradient);
  56969. }
  56970. }
  56971. var sizeGradients = particleSystem.getSizeGradients();
  56972. if (sizeGradients) {
  56973. serializationObject.sizeGradients = [];
  56974. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56975. var sizeGradient = sizeGradients_1[_a];
  56976. var serializedGradient = {
  56977. gradient: sizeGradient.gradient,
  56978. factor1: sizeGradient.factor1
  56979. };
  56980. if (sizeGradient.factor2 !== undefined) {
  56981. serializedGradient.factor2 = sizeGradient.factor2;
  56982. }
  56983. serializationObject.sizeGradients.push(serializedGradient);
  56984. }
  56985. }
  56986. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56987. if (angularSpeedGradients) {
  56988. serializationObject.angularSpeedGradients = [];
  56989. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56990. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56991. var serializedGradient = {
  56992. gradient: angularSpeedGradient.gradient,
  56993. factor1: angularSpeedGradient.factor1
  56994. };
  56995. if (angularSpeedGradient.factor2 !== undefined) {
  56996. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56997. }
  56998. serializationObject.angularSpeedGradients.push(serializedGradient);
  56999. }
  57000. }
  57001. var velocityGradients = particleSystem.getVelocityGradients();
  57002. if (velocityGradients) {
  57003. serializationObject.velocityGradients = [];
  57004. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  57005. var velocityGradient = velocityGradients_1[_c];
  57006. var serializedGradient = {
  57007. gradient: velocityGradient.gradient,
  57008. factor1: velocityGradient.factor1
  57009. };
  57010. if (velocityGradient.factor2 !== undefined) {
  57011. serializedGradient.factor2 = velocityGradient.factor2;
  57012. }
  57013. serializationObject.velocityGradients.push(serializedGradient);
  57014. }
  57015. }
  57016. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57017. if (limitVelocityGradients) {
  57018. serializationObject.limitVelocityGradients = [];
  57019. for (var _d = 0, limitVelocityGradients_1 = limitVelocityGradients; _d < limitVelocityGradients_1.length; _d++) {
  57020. var limitVelocityGradient = limitVelocityGradients_1[_d];
  57021. var serializedGradient = {
  57022. gradient: limitVelocityGradient.gradient,
  57023. factor1: limitVelocityGradient.factor1
  57024. };
  57025. if (limitVelocityGradient.factor2 !== undefined) {
  57026. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57027. }
  57028. serializationObject.limitVelocityGradients.push(serializedGradient);
  57029. }
  57030. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57031. }
  57032. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57033. var noiseTexture = particleSystem.noiseTexture;
  57034. serializationObject.noiseTexture = noiseTexture.serialize();
  57035. }
  57036. };
  57037. /** @hidden */
  57038. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57039. // Texture
  57040. if (parsedParticleSystem.textureName) {
  57041. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57042. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57043. }
  57044. // Emitter
  57045. if (parsedParticleSystem.emitterId === undefined) {
  57046. particleSystem.emitter = BABYLON.Vector3.Zero();
  57047. }
  57048. else if (parsedParticleSystem.emitterId) {
  57049. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57050. }
  57051. else {
  57052. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57053. }
  57054. // Misc.
  57055. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57056. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57057. }
  57058. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57059. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57060. }
  57061. // Animations
  57062. if (parsedParticleSystem.animations) {
  57063. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57064. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57065. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57066. }
  57067. }
  57068. if (parsedParticleSystem.autoAnimate) {
  57069. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57070. }
  57071. // Particle system
  57072. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57073. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57074. particleSystem.minSize = parsedParticleSystem.minSize;
  57075. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57076. if (parsedParticleSystem.minScaleX) {
  57077. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57078. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57079. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57080. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57081. }
  57082. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57083. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57084. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57085. }
  57086. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57087. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57088. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57089. }
  57090. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57091. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57092. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57093. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57094. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57095. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57096. if (parsedParticleSystem.noiseStrength) {
  57097. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57098. }
  57099. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57100. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57101. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57102. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57103. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57104. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57105. if (parsedParticleSystem.colorGradients) {
  57106. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57107. var colorGradient = _a[_i];
  57108. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57109. }
  57110. }
  57111. if (parsedParticleSystem.sizeGradients) {
  57112. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  57113. var sizeGradient = _c[_b];
  57114. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57115. }
  57116. }
  57117. if (parsedParticleSystem.angularSpeedGradients) {
  57118. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  57119. var angularSpeedGradient = _e[_d];
  57120. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57121. }
  57122. }
  57123. if (parsedParticleSystem.velocityGradients) {
  57124. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  57125. var velocityGradient = _g[_f];
  57126. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57127. }
  57128. }
  57129. if (parsedParticleSystem.limitVelocityGradients) {
  57130. for (var _h = 0, _j = parsedParticleSystem.limitVelocityGradients; _h < _j.length; _h++) {
  57131. var limitVelocityGradient = _j[_h];
  57132. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57133. }
  57134. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57135. }
  57136. if (parsedParticleSystem.noiseTexture) {
  57137. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57138. }
  57139. // Emitter
  57140. var emitterType;
  57141. if (parsedParticleSystem.particleEmitterType) {
  57142. switch (parsedParticleSystem.particleEmitterType.type) {
  57143. case "SphereParticleEmitter":
  57144. emitterType = new BABYLON.SphereParticleEmitter();
  57145. break;
  57146. case "SphereDirectedParticleEmitter":
  57147. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57148. break;
  57149. case "ConeEmitter":
  57150. case "ConeParticleEmitter":
  57151. emitterType = new BABYLON.ConeParticleEmitter();
  57152. break;
  57153. case "BoxEmitter":
  57154. case "BoxParticleEmitter":
  57155. default:
  57156. emitterType = new BABYLON.BoxParticleEmitter();
  57157. break;
  57158. }
  57159. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57160. }
  57161. else {
  57162. emitterType = new BABYLON.BoxParticleEmitter();
  57163. emitterType.parse(parsedParticleSystem);
  57164. }
  57165. particleSystem.particleEmitterType = emitterType;
  57166. // Animation sheet
  57167. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57168. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57169. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57170. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57171. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57172. };
  57173. /**
  57174. * Parses a JSON object to create a particle system.
  57175. * @param parsedParticleSystem The JSON object to parse
  57176. * @param scene The scene to create the particle system in
  57177. * @param rootUrl The root url to use to load external dependencies like texture
  57178. * @returns the Parsed particle system
  57179. */
  57180. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57181. var name = parsedParticleSystem.name;
  57182. var custom = null;
  57183. var program = null;
  57184. if (parsedParticleSystem.customShader) {
  57185. program = parsedParticleSystem.customShader;
  57186. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57187. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57188. }
  57189. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57190. particleSystem.customShader = program;
  57191. if (parsedParticleSystem.id) {
  57192. particleSystem.id = parsedParticleSystem.id;
  57193. }
  57194. // Auto start
  57195. if (parsedParticleSystem.preventAutoStart) {
  57196. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57197. }
  57198. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57199. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57200. if (!particleSystem.preventAutoStart) {
  57201. particleSystem.start();
  57202. }
  57203. return particleSystem;
  57204. };
  57205. return ParticleSystem;
  57206. }(BABYLON.BaseParticleSystem));
  57207. BABYLON.ParticleSystem = ParticleSystem;
  57208. })(BABYLON || (BABYLON = {}));
  57209. //# sourceMappingURL=babylon.particleSystem.js.map
  57210. var BABYLON;
  57211. (function (BABYLON) {
  57212. /**
  57213. * Particle emitter emitting particles from the inside of a box.
  57214. * It emits the particles randomly between 2 given directions.
  57215. */
  57216. var BoxParticleEmitter = /** @class */ (function () {
  57217. /**
  57218. * Creates a new instance BoxParticleEmitter
  57219. */
  57220. function BoxParticleEmitter() {
  57221. /**
  57222. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57223. */
  57224. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57225. /**
  57226. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57227. */
  57228. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57229. /**
  57230. * 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.
  57231. */
  57232. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57233. /**
  57234. * 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.
  57235. */
  57236. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57237. }
  57238. /**
  57239. * Called by the particle System when the direction is computed for the created particle.
  57240. * @param worldMatrix is the world matrix of the particle system
  57241. * @param directionToUpdate is the direction vector to update with the result
  57242. * @param particle is the particle we are computed the direction for
  57243. */
  57244. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57245. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57246. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57247. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57248. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57249. };
  57250. /**
  57251. * Called by the particle System when the position is computed for the created particle.
  57252. * @param worldMatrix is the world matrix of the particle system
  57253. * @param positionToUpdate is the position vector to update with the result
  57254. * @param particle is the particle we are computed the position for
  57255. */
  57256. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57257. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57258. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57259. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57260. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57261. };
  57262. /**
  57263. * Clones the current emitter and returns a copy of it
  57264. * @returns the new emitter
  57265. */
  57266. BoxParticleEmitter.prototype.clone = function () {
  57267. var newOne = new BoxParticleEmitter();
  57268. BABYLON.Tools.DeepCopy(this, newOne);
  57269. return newOne;
  57270. };
  57271. /**
  57272. * Called by the GPUParticleSystem to setup the update shader
  57273. * @param effect defines the update shader
  57274. */
  57275. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57276. effect.setVector3("direction1", this.direction1);
  57277. effect.setVector3("direction2", this.direction2);
  57278. effect.setVector3("minEmitBox", this.minEmitBox);
  57279. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57280. };
  57281. /**
  57282. * Returns a string to use to update the GPU particles update shader
  57283. * @returns a string containng the defines string
  57284. */
  57285. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57286. return "#define BOXEMITTER";
  57287. };
  57288. /**
  57289. * Returns the string "BoxParticleEmitter"
  57290. * @returns a string containing the class name
  57291. */
  57292. BoxParticleEmitter.prototype.getClassName = function () {
  57293. return "BoxParticleEmitter";
  57294. };
  57295. /**
  57296. * Serializes the particle system to a JSON object.
  57297. * @returns the JSON object
  57298. */
  57299. BoxParticleEmitter.prototype.serialize = function () {
  57300. var serializationObject = {};
  57301. serializationObject.type = this.getClassName();
  57302. serializationObject.direction1 = this.direction1.asArray();
  57303. serializationObject.direction2 = this.direction2.asArray();
  57304. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57305. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57306. return serializationObject;
  57307. };
  57308. /**
  57309. * Parse properties from a JSON object
  57310. * @param serializationObject defines the JSON object
  57311. */
  57312. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57313. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57314. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57315. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57316. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57317. };
  57318. return BoxParticleEmitter;
  57319. }());
  57320. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57321. })(BABYLON || (BABYLON = {}));
  57322. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57323. var BABYLON;
  57324. (function (BABYLON) {
  57325. /**
  57326. * Particle emitter emitting particles from the inside of a cone.
  57327. * It emits the particles alongside the cone volume from the base to the particle.
  57328. * The emission direction might be randomized.
  57329. */
  57330. var ConeParticleEmitter = /** @class */ (function () {
  57331. /**
  57332. * Creates a new instance ConeParticleEmitter
  57333. * @param radius the radius of the emission cone (1 by default)
  57334. * @param angles the cone base angle (PI by default)
  57335. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57336. */
  57337. function ConeParticleEmitter(radius, angle,
  57338. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57339. directionRandomizer) {
  57340. if (radius === void 0) { radius = 1; }
  57341. if (angle === void 0) { angle = Math.PI; }
  57342. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57343. this.directionRandomizer = directionRandomizer;
  57344. /**
  57345. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  57346. */
  57347. this.radiusRange = 1;
  57348. /**
  57349. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  57350. */
  57351. this.heightRange = 1;
  57352. /**
  57353. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  57354. */
  57355. this.emitFromSpawnPointOnly = false;
  57356. this.angle = angle;
  57357. this.radius = radius;
  57358. }
  57359. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57360. /**
  57361. * Gets or sets the radius of the emission cone
  57362. */
  57363. get: function () {
  57364. return this._radius;
  57365. },
  57366. set: function (value) {
  57367. this._radius = value;
  57368. this._buildHeight();
  57369. },
  57370. enumerable: true,
  57371. configurable: true
  57372. });
  57373. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57374. /**
  57375. * Gets or sets the angle of the emission cone
  57376. */
  57377. get: function () {
  57378. return this._angle;
  57379. },
  57380. set: function (value) {
  57381. this._angle = value;
  57382. this._buildHeight();
  57383. },
  57384. enumerable: true,
  57385. configurable: true
  57386. });
  57387. ConeParticleEmitter.prototype._buildHeight = function () {
  57388. if (this._angle !== 0) {
  57389. this._height = this._radius / Math.tan(this._angle / 2);
  57390. }
  57391. else {
  57392. this._height = 1;
  57393. }
  57394. };
  57395. /**
  57396. * Called by the particle System when the direction is computed for the created particle.
  57397. * @param worldMatrix is the world matrix of the particle system
  57398. * @param directionToUpdate is the direction vector to update with the result
  57399. * @param particle is the particle we are computed the direction for
  57400. */
  57401. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57402. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  57403. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  57404. }
  57405. else {
  57406. // measure the direction Vector from the emitter to the particle.
  57407. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57408. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57409. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57410. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57411. direction.x += randX;
  57412. direction.y += randY;
  57413. direction.z += randZ;
  57414. direction.normalize();
  57415. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57416. }
  57417. };
  57418. /**
  57419. * Called by the particle System when the position is computed for the created particle.
  57420. * @param worldMatrix is the world matrix of the particle system
  57421. * @param positionToUpdate is the position vector to update with the result
  57422. * @param particle is the particle we are computed the position for
  57423. */
  57424. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57425. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57426. var h;
  57427. if (!this.emitFromSpawnPointOnly) {
  57428. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  57429. // Better distribution in a cone at normal angles.
  57430. h = 1 - h * h;
  57431. }
  57432. else {
  57433. h = 0.0001;
  57434. }
  57435. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  57436. radius = radius * h;
  57437. var randX = radius * Math.sin(s);
  57438. var randZ = radius * Math.cos(s);
  57439. var randY = h * this._height;
  57440. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57441. };
  57442. /**
  57443. * Clones the current emitter and returns a copy of it
  57444. * @returns the new emitter
  57445. */
  57446. ConeParticleEmitter.prototype.clone = function () {
  57447. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57448. BABYLON.Tools.DeepCopy(this, newOne);
  57449. return newOne;
  57450. };
  57451. /**
  57452. * Called by the GPUParticleSystem to setup the update shader
  57453. * @param effect defines the update shader
  57454. */
  57455. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57456. effect.setFloat2("radius", this._radius, this.radiusRange);
  57457. effect.setFloat("coneAngle", this._angle);
  57458. effect.setFloat2("height", this._height, this.heightRange);
  57459. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57460. };
  57461. /**
  57462. * Returns a string to use to update the GPU particles update shader
  57463. * @returns a string containng the defines string
  57464. */
  57465. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57466. var defines = "#define CONEEMITTER";
  57467. if (this.emitFromSpawnPointOnly) {
  57468. defines += "\n#define CONEEMITTERSPAWNPOINT";
  57469. }
  57470. return defines;
  57471. };
  57472. /**
  57473. * Returns the string "ConeParticleEmitter"
  57474. * @returns a string containing the class name
  57475. */
  57476. ConeParticleEmitter.prototype.getClassName = function () {
  57477. return "ConeParticleEmitter";
  57478. };
  57479. /**
  57480. * Serializes the particle system to a JSON object.
  57481. * @returns the JSON object
  57482. */
  57483. ConeParticleEmitter.prototype.serialize = function () {
  57484. var serializationObject = {};
  57485. serializationObject.type = this.getClassName();
  57486. serializationObject.radius = this._radius;
  57487. serializationObject.angle = this._angle;
  57488. serializationObject.directionRandomizer = this.directionRandomizer;
  57489. return serializationObject;
  57490. };
  57491. /**
  57492. * Parse properties from a JSON object
  57493. * @param serializationObject defines the JSON object
  57494. */
  57495. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57496. this.radius = serializationObject.radius;
  57497. this.angle = serializationObject.angle;
  57498. this.directionRandomizer = serializationObject.directionRandomizer;
  57499. };
  57500. return ConeParticleEmitter;
  57501. }());
  57502. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57503. })(BABYLON || (BABYLON = {}));
  57504. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57505. var BABYLON;
  57506. (function (BABYLON) {
  57507. /**
  57508. * Particle emitter emitting particles from the inside of a sphere.
  57509. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57510. */
  57511. var SphereParticleEmitter = /** @class */ (function () {
  57512. /**
  57513. * Creates a new instance SphereParticleEmitter
  57514. * @param radius the radius of the emission sphere (1 by default)
  57515. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57516. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57517. */
  57518. function SphereParticleEmitter(
  57519. /**
  57520. * The radius of the emission sphere.
  57521. */
  57522. radius,
  57523. /**
  57524. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57525. */
  57526. radiusRange,
  57527. /**
  57528. * How much to randomize the particle direction [0-1].
  57529. */
  57530. directionRandomizer) {
  57531. if (radius === void 0) { radius = 1; }
  57532. if (radiusRange === void 0) { radiusRange = 1; }
  57533. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57534. this.radius = radius;
  57535. this.radiusRange = radiusRange;
  57536. this.directionRandomizer = directionRandomizer;
  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. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57545. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57546. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57547. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57548. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57549. direction.x += randX;
  57550. direction.y += randY;
  57551. direction.z += randZ;
  57552. direction.normalize();
  57553. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57554. };
  57555. /**
  57556. * Called by the particle System when the position is computed for the created particle.
  57557. * @param worldMatrix is the world matrix of the particle system
  57558. * @param positionToUpdate is the position vector to update with the result
  57559. * @param particle is the particle we are computed the position for
  57560. */
  57561. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57562. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57563. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57564. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57565. var theta = Math.acos(2 * v - 1);
  57566. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57567. var randY = randRadius * Math.cos(theta);
  57568. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57569. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57570. };
  57571. /**
  57572. * Clones the current emitter and returns a copy of it
  57573. * @returns the new emitter
  57574. */
  57575. SphereParticleEmitter.prototype.clone = function () {
  57576. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57577. BABYLON.Tools.DeepCopy(this, newOne);
  57578. return newOne;
  57579. };
  57580. /**
  57581. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57582. * @param effect defines the update shader
  57583. */
  57584. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57585. effect.setFloat("radius", this.radius);
  57586. effect.setFloat("radiusRange", this.radiusRange);
  57587. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57588. };
  57589. /**
  57590. * Returns a string to use to update the GPU particles update shader
  57591. * @returns a string containng the defines string
  57592. */
  57593. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57594. return "#define SPHEREEMITTER";
  57595. };
  57596. /**
  57597. * Returns the string "SphereParticleEmitter"
  57598. * @returns a string containing the class name
  57599. */
  57600. SphereParticleEmitter.prototype.getClassName = function () {
  57601. return "SphereParticleEmitter";
  57602. };
  57603. /**
  57604. * Serializes the particle system to a JSON object.
  57605. * @returns the JSON object
  57606. */
  57607. SphereParticleEmitter.prototype.serialize = function () {
  57608. var serializationObject = {};
  57609. serializationObject.type = this.getClassName();
  57610. serializationObject.radius = this.radius;
  57611. serializationObject.radiusRange = this.radiusRange;
  57612. serializationObject.directionRandomizer = this.directionRandomizer;
  57613. return serializationObject;
  57614. };
  57615. /**
  57616. * Parse properties from a JSON object
  57617. * @param serializationObject defines the JSON object
  57618. */
  57619. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57620. this.radius = serializationObject.radius;
  57621. this.radiusRange = serializationObject.radiusRange;
  57622. this.directionRandomizer = serializationObject.directionRandomizer;
  57623. };
  57624. return SphereParticleEmitter;
  57625. }());
  57626. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57627. /**
  57628. * Particle emitter emitting particles from the inside of a sphere.
  57629. * It emits the particles randomly between two vectors.
  57630. */
  57631. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57632. __extends(SphereDirectedParticleEmitter, _super);
  57633. /**
  57634. * Creates a new instance SphereDirectedParticleEmitter
  57635. * @param radius the radius of the emission sphere (1 by default)
  57636. * @param direction1 the min limit of the emission direction (up vector by default)
  57637. * @param direction2 the max limit of the emission direction (up vector by default)
  57638. */
  57639. function SphereDirectedParticleEmitter(radius,
  57640. /**
  57641. * The min limit of the emission direction.
  57642. */
  57643. direction1,
  57644. /**
  57645. * The max limit of the emission direction.
  57646. */
  57647. direction2) {
  57648. if (radius === void 0) { radius = 1; }
  57649. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57650. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57651. var _this = _super.call(this, radius) || this;
  57652. _this.direction1 = direction1;
  57653. _this.direction2 = direction2;
  57654. return _this;
  57655. }
  57656. /**
  57657. * Called by the particle System when the direction is computed for the created particle.
  57658. * @param worldMatrix is the world matrix of the particle system
  57659. * @param directionToUpdate is the direction vector to update with the result
  57660. * @param particle is the particle we are computed the direction for
  57661. */
  57662. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57663. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57664. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57665. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57666. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57667. };
  57668. /**
  57669. * Clones the current emitter and returns a copy of it
  57670. * @returns the new emitter
  57671. */
  57672. SphereDirectedParticleEmitter.prototype.clone = function () {
  57673. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57674. BABYLON.Tools.DeepCopy(this, newOne);
  57675. return newOne;
  57676. };
  57677. /**
  57678. * Called by the GPUParticleSystem to setup the update shader
  57679. * @param effect defines the update shader
  57680. */
  57681. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57682. effect.setFloat("radius", this.radius);
  57683. effect.setFloat("radiusRange", this.radiusRange);
  57684. effect.setVector3("direction1", this.direction1);
  57685. effect.setVector3("direction2", this.direction2);
  57686. };
  57687. /**
  57688. * Returns a string to use to update the GPU particles update shader
  57689. * @returns a string containng the defines string
  57690. */
  57691. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57692. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57693. };
  57694. /**
  57695. * Returns the string "SphereDirectedParticleEmitter"
  57696. * @returns a string containing the class name
  57697. */
  57698. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57699. return "SphereDirectedParticleEmitter";
  57700. };
  57701. /**
  57702. * Serializes the particle system to a JSON object.
  57703. * @returns the JSON object
  57704. */
  57705. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57706. var serializationObject = _super.prototype.serialize.call(this);
  57707. serializationObject.direction1 = this.direction1.asArray();
  57708. serializationObject.direction2 = this.direction2.asArray();
  57709. return serializationObject;
  57710. };
  57711. /**
  57712. * Parse properties from a JSON object
  57713. * @param serializationObject defines the JSON object
  57714. */
  57715. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57716. _super.prototype.parse.call(this, serializationObject);
  57717. this.direction1.copyFrom(serializationObject.direction1);
  57718. this.direction2.copyFrom(serializationObject.direction2);
  57719. };
  57720. return SphereDirectedParticleEmitter;
  57721. }(SphereParticleEmitter));
  57722. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57723. })(BABYLON || (BABYLON = {}));
  57724. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57725. var BABYLON;
  57726. (function (BABYLON) {
  57727. /**
  57728. * Particle emitter emitting particles from the inside of a hemisphere.
  57729. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  57730. */
  57731. var HemisphericParticleEmitter = /** @class */ (function () {
  57732. /**
  57733. * Creates a new instance HemisphericParticleEmitter
  57734. * @param radius the radius of the emission hemisphere (1 by default)
  57735. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57736. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57737. */
  57738. function HemisphericParticleEmitter(
  57739. /**
  57740. * The radius of the emission hemisphere.
  57741. */
  57742. radius,
  57743. /**
  57744. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57745. */
  57746. radiusRange,
  57747. /**
  57748. * How much to randomize the particle direction [0-1].
  57749. */
  57750. directionRandomizer) {
  57751. if (radius === void 0) { radius = 1; }
  57752. if (radiusRange === void 0) { radiusRange = 1; }
  57753. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57754. this.radius = radius;
  57755. this.radiusRange = radiusRange;
  57756. this.directionRandomizer = directionRandomizer;
  57757. }
  57758. /**
  57759. * Called by the particle System when the direction is computed for the created particle.
  57760. * @param worldMatrix is the world matrix of the particle system
  57761. * @param directionToUpdate is the direction vector to update with the result
  57762. * @param particle is the particle we are computed the direction for
  57763. */
  57764. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57765. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57766. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57767. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57768. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57769. direction.x += randX;
  57770. direction.y += randY;
  57771. direction.z += randZ;
  57772. direction.normalize();
  57773. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57774. };
  57775. /**
  57776. * Called by the particle System when the position is computed for the created particle.
  57777. * @param worldMatrix is the world matrix of the particle system
  57778. * @param positionToUpdate is the position vector to update with the result
  57779. * @param particle is the particle we are computed the position for
  57780. */
  57781. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57782. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57783. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57784. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57785. var theta = Math.acos(2 * v - 1);
  57786. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57787. var randY = randRadius * Math.cos(theta);
  57788. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57789. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  57790. };
  57791. /**
  57792. * Clones the current emitter and returns a copy of it
  57793. * @returns the new emitter
  57794. */
  57795. HemisphericParticleEmitter.prototype.clone = function () {
  57796. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  57797. BABYLON.Tools.DeepCopy(this, newOne);
  57798. return newOne;
  57799. };
  57800. /**
  57801. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57802. * @param effect defines the update shader
  57803. */
  57804. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  57805. effect.setFloat("radius", this.radius);
  57806. effect.setFloat("radiusRange", this.radiusRange);
  57807. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57808. };
  57809. /**
  57810. * Returns a string to use to update the GPU particles update shader
  57811. * @returns a string containng the defines string
  57812. */
  57813. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  57814. return "#define HEMISPHERICEMITTER";
  57815. };
  57816. /**
  57817. * Returns the string "HemisphericParticleEmitter"
  57818. * @returns a string containing the class name
  57819. */
  57820. HemisphericParticleEmitter.prototype.getClassName = function () {
  57821. return "HemisphericParticleEmitter";
  57822. };
  57823. /**
  57824. * Serializes the particle system to a JSON object.
  57825. * @returns the JSON object
  57826. */
  57827. HemisphericParticleEmitter.prototype.serialize = function () {
  57828. var serializationObject = {};
  57829. serializationObject.type = this.getClassName();
  57830. serializationObject.radius = this.radius;
  57831. serializationObject.radiusRange = this.radiusRange;
  57832. serializationObject.directionRandomizer = this.directionRandomizer;
  57833. return serializationObject;
  57834. };
  57835. /**
  57836. * Parse properties from a JSON object
  57837. * @param serializationObject defines the JSON object
  57838. */
  57839. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  57840. this.radius = serializationObject.radius;
  57841. this.radiusRange = serializationObject.radiusRange;
  57842. this.directionRandomizer = serializationObject.directionRandomizer;
  57843. };
  57844. return HemisphericParticleEmitter;
  57845. }());
  57846. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  57847. })(BABYLON || (BABYLON = {}));
  57848. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  57849. var BABYLON;
  57850. (function (BABYLON) {
  57851. /**
  57852. * Particle emitter emitting particles from a point.
  57853. * It emits the particles randomly between 2 given directions.
  57854. */
  57855. var PointParticleEmitter = /** @class */ (function () {
  57856. /**
  57857. * Creates a new instance PointParticleEmitter
  57858. */
  57859. function PointParticleEmitter() {
  57860. /**
  57861. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57862. */
  57863. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57864. /**
  57865. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57866. */
  57867. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57868. }
  57869. /**
  57870. * Called by the particle System when the direction is computed for the created particle.
  57871. * @param worldMatrix is the world matrix of the particle system
  57872. * @param directionToUpdate is the direction vector to update with the result
  57873. * @param particle is the particle we are computed the direction for
  57874. */
  57875. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57876. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57877. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57878. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57879. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57880. };
  57881. /**
  57882. * Called by the particle System when the position is computed for the created particle.
  57883. * @param worldMatrix is the world matrix of the particle system
  57884. * @param positionToUpdate is the position vector to update with the result
  57885. * @param particle is the particle we are computed the position for
  57886. */
  57887. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57888. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  57889. };
  57890. /**
  57891. * Clones the current emitter and returns a copy of it
  57892. * @returns the new emitter
  57893. */
  57894. PointParticleEmitter.prototype.clone = function () {
  57895. var newOne = new PointParticleEmitter();
  57896. BABYLON.Tools.DeepCopy(this, newOne);
  57897. return newOne;
  57898. };
  57899. /**
  57900. * Called by the GPUParticleSystem to setup the update shader
  57901. * @param effect defines the update shader
  57902. */
  57903. PointParticleEmitter.prototype.applyToShader = function (effect) {
  57904. effect.setVector3("direction1", this.direction1);
  57905. effect.setVector3("direction2", this.direction2);
  57906. };
  57907. /**
  57908. * Returns a string to use to update the GPU particles update shader
  57909. * @returns a string containng the defines string
  57910. */
  57911. PointParticleEmitter.prototype.getEffectDefines = function () {
  57912. return "#define POINTEMITTER";
  57913. };
  57914. /**
  57915. * Returns the string "PointParticleEmitter"
  57916. * @returns a string containing the class name
  57917. */
  57918. PointParticleEmitter.prototype.getClassName = function () {
  57919. return "PointParticleEmitter";
  57920. };
  57921. /**
  57922. * Serializes the particle system to a JSON object.
  57923. * @returns the JSON object
  57924. */
  57925. PointParticleEmitter.prototype.serialize = function () {
  57926. var serializationObject = {};
  57927. serializationObject.type = this.getClassName();
  57928. serializationObject.direction1 = this.direction1.asArray();
  57929. serializationObject.direction2 = this.direction2.asArray();
  57930. return serializationObject;
  57931. };
  57932. /**
  57933. * Parse properties from a JSON object
  57934. * @param serializationObject defines the JSON object
  57935. */
  57936. PointParticleEmitter.prototype.parse = function (serializationObject) {
  57937. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57938. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57939. };
  57940. return PointParticleEmitter;
  57941. }());
  57942. BABYLON.PointParticleEmitter = PointParticleEmitter;
  57943. })(BABYLON || (BABYLON = {}));
  57944. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  57945. var BABYLON;
  57946. (function (BABYLON) {
  57947. // Adds the parsers to the scene parsers.
  57948. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57949. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  57950. if (!individualParser) {
  57951. return;
  57952. }
  57953. // Particles Systems
  57954. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57955. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57956. var parsedParticleSystem = parsedData.particleSystems[index];
  57957. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  57958. }
  57959. }
  57960. });
  57961. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  57962. if (parsedParticleSystem.activeParticleCount) {
  57963. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57964. return ps;
  57965. }
  57966. else {
  57967. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57968. return ps;
  57969. }
  57970. });
  57971. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57972. if (uniformsNames === void 0) { uniformsNames = []; }
  57973. if (samplers === void 0) { samplers = []; }
  57974. if (defines === void 0) { defines = ""; }
  57975. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57976. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57977. if (defines.indexOf(" BILLBOARD") === -1) {
  57978. defines += "\n#define BILLBOARD\n";
  57979. }
  57980. if (samplers.indexOf("diffuseSampler") === -1) {
  57981. samplers.push("diffuseSampler");
  57982. }
  57983. return this.createEffect({
  57984. vertex: "particles",
  57985. fragmentElement: fragmentName
  57986. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57987. };
  57988. })(BABYLON || (BABYLON = {}));
  57989. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57990. var BABYLON;
  57991. (function (BABYLON) {
  57992. var ShaderMaterial = /** @class */ (function (_super) {
  57993. __extends(ShaderMaterial, _super);
  57994. function ShaderMaterial(name, scene, shaderPath, options) {
  57995. var _this = _super.call(this, name, scene) || this;
  57996. _this._textures = {};
  57997. _this._textureArrays = {};
  57998. _this._floats = {};
  57999. _this._ints = {};
  58000. _this._floatsArrays = {};
  58001. _this._colors3 = {};
  58002. _this._colors3Arrays = {};
  58003. _this._colors4 = {};
  58004. _this._vectors2 = {};
  58005. _this._vectors3 = {};
  58006. _this._vectors4 = {};
  58007. _this._matrices = {};
  58008. _this._matrices3x3 = {};
  58009. _this._matrices2x2 = {};
  58010. _this._vectors2Arrays = {};
  58011. _this._vectors3Arrays = {};
  58012. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58013. _this._shaderPath = shaderPath;
  58014. options.needAlphaBlending = options.needAlphaBlending || false;
  58015. options.needAlphaTesting = options.needAlphaTesting || false;
  58016. options.attributes = options.attributes || ["position", "normal", "uv"];
  58017. options.uniforms = options.uniforms || ["worldViewProjection"];
  58018. options.uniformBuffers = options.uniformBuffers || [];
  58019. options.samplers = options.samplers || [];
  58020. options.defines = options.defines || [];
  58021. _this._options = options;
  58022. return _this;
  58023. }
  58024. ShaderMaterial.prototype.getClassName = function () {
  58025. return "ShaderMaterial";
  58026. };
  58027. ShaderMaterial.prototype.needAlphaBlending = function () {
  58028. return this._options.needAlphaBlending;
  58029. };
  58030. ShaderMaterial.prototype.needAlphaTesting = function () {
  58031. return this._options.needAlphaTesting;
  58032. };
  58033. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58034. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58035. this._options.uniforms.push(uniformName);
  58036. }
  58037. };
  58038. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58039. if (this._options.samplers.indexOf(name) === -1) {
  58040. this._options.samplers.push(name);
  58041. }
  58042. this._textures[name] = texture;
  58043. return this;
  58044. };
  58045. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58046. if (this._options.samplers.indexOf(name) === -1) {
  58047. this._options.samplers.push(name);
  58048. }
  58049. this._checkUniform(name);
  58050. this._textureArrays[name] = textures;
  58051. return this;
  58052. };
  58053. ShaderMaterial.prototype.setFloat = function (name, value) {
  58054. this._checkUniform(name);
  58055. this._floats[name] = value;
  58056. return this;
  58057. };
  58058. ShaderMaterial.prototype.setInt = function (name, value) {
  58059. this._checkUniform(name);
  58060. this._ints[name] = value;
  58061. return this;
  58062. };
  58063. ShaderMaterial.prototype.setFloats = function (name, value) {
  58064. this._checkUniform(name);
  58065. this._floatsArrays[name] = value;
  58066. return this;
  58067. };
  58068. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58069. this._checkUniform(name);
  58070. this._colors3[name] = value;
  58071. return this;
  58072. };
  58073. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58074. this._checkUniform(name);
  58075. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58076. color.toArray(arr, arr.length);
  58077. return arr;
  58078. }, []);
  58079. return this;
  58080. };
  58081. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58082. this._checkUniform(name);
  58083. this._colors4[name] = value;
  58084. return this;
  58085. };
  58086. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58087. this._checkUniform(name);
  58088. this._vectors2[name] = value;
  58089. return this;
  58090. };
  58091. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58092. this._checkUniform(name);
  58093. this._vectors3[name] = value;
  58094. return this;
  58095. };
  58096. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58097. this._checkUniform(name);
  58098. this._vectors4[name] = value;
  58099. return this;
  58100. };
  58101. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58102. this._checkUniform(name);
  58103. this._matrices[name] = value;
  58104. return this;
  58105. };
  58106. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58107. this._checkUniform(name);
  58108. this._matrices3x3[name] = value;
  58109. return this;
  58110. };
  58111. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58112. this._checkUniform(name);
  58113. this._matrices2x2[name] = value;
  58114. return this;
  58115. };
  58116. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58117. this._checkUniform(name);
  58118. this._vectors2Arrays[name] = value;
  58119. return this;
  58120. };
  58121. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58122. this._checkUniform(name);
  58123. this._vectors3Arrays[name] = value;
  58124. return this;
  58125. };
  58126. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58127. if (!mesh) {
  58128. return true;
  58129. }
  58130. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58131. return false;
  58132. }
  58133. return false;
  58134. };
  58135. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58136. var scene = this.getScene();
  58137. var engine = scene.getEngine();
  58138. if (!this.checkReadyOnEveryCall) {
  58139. if (this._renderId === scene.getRenderId()) {
  58140. if (this._checkCache(scene, mesh, useInstances)) {
  58141. return true;
  58142. }
  58143. }
  58144. }
  58145. // Instances
  58146. var defines = [];
  58147. var attribs = [];
  58148. var fallbacks = new BABYLON.EffectFallbacks();
  58149. if (useInstances) {
  58150. defines.push("#define INSTANCES");
  58151. }
  58152. for (var index = 0; index < this._options.defines.length; index++) {
  58153. defines.push(this._options.defines[index]);
  58154. }
  58155. for (var index = 0; index < this._options.attributes.length; index++) {
  58156. attribs.push(this._options.attributes[index]);
  58157. }
  58158. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58159. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58160. defines.push("#define VERTEXCOLOR");
  58161. }
  58162. // Bones
  58163. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58164. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58165. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58166. if (mesh.numBoneInfluencers > 4) {
  58167. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58168. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58169. }
  58170. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58171. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58172. fallbacks.addCPUSkinningFallback(0, mesh);
  58173. if (this._options.uniforms.indexOf("mBones") === -1) {
  58174. this._options.uniforms.push("mBones");
  58175. }
  58176. }
  58177. else {
  58178. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58179. }
  58180. // Textures
  58181. for (var name in this._textures) {
  58182. if (!this._textures[name].isReady()) {
  58183. return false;
  58184. }
  58185. }
  58186. // Alpha test
  58187. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58188. defines.push("#define ALPHATEST");
  58189. }
  58190. var previousEffect = this._effect;
  58191. var join = defines.join("\n");
  58192. this._effect = engine.createEffect(this._shaderPath, {
  58193. attributes: attribs,
  58194. uniformsNames: this._options.uniforms,
  58195. uniformBuffersNames: this._options.uniformBuffers,
  58196. samplers: this._options.samplers,
  58197. defines: join,
  58198. fallbacks: fallbacks,
  58199. onCompiled: this.onCompiled,
  58200. onError: this.onError
  58201. }, engine);
  58202. if (!this._effect.isReady()) {
  58203. return false;
  58204. }
  58205. if (previousEffect !== this._effect) {
  58206. scene.resetCachedMaterial();
  58207. }
  58208. this._renderId = scene.getRenderId();
  58209. return true;
  58210. };
  58211. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58212. var scene = this.getScene();
  58213. if (!this._effect) {
  58214. return;
  58215. }
  58216. if (this._options.uniforms.indexOf("world") !== -1) {
  58217. this._effect.setMatrix("world", world);
  58218. }
  58219. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58220. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58221. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58222. }
  58223. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58224. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58225. }
  58226. };
  58227. ShaderMaterial.prototype.bind = function (world, mesh) {
  58228. // Std values
  58229. this.bindOnlyWorldMatrix(world);
  58230. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58231. if (this._options.uniforms.indexOf("view") !== -1) {
  58232. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58233. }
  58234. if (this._options.uniforms.indexOf("projection") !== -1) {
  58235. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58236. }
  58237. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58238. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58239. }
  58240. // Bones
  58241. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58242. var name;
  58243. // Texture
  58244. for (name in this._textures) {
  58245. this._effect.setTexture(name, this._textures[name]);
  58246. }
  58247. // Texture arrays
  58248. for (name in this._textureArrays) {
  58249. this._effect.setTextureArray(name, this._textureArrays[name]);
  58250. }
  58251. // Int
  58252. for (name in this._ints) {
  58253. this._effect.setInt(name, this._ints[name]);
  58254. }
  58255. // Float
  58256. for (name in this._floats) {
  58257. this._effect.setFloat(name, this._floats[name]);
  58258. }
  58259. // Floats
  58260. for (name in this._floatsArrays) {
  58261. this._effect.setArray(name, this._floatsArrays[name]);
  58262. }
  58263. // Color3
  58264. for (name in this._colors3) {
  58265. this._effect.setColor3(name, this._colors3[name]);
  58266. }
  58267. for (name in this._colors3Arrays) {
  58268. this._effect.setArray3(name, this._colors3Arrays[name]);
  58269. }
  58270. // Color4
  58271. for (name in this._colors4) {
  58272. var color = this._colors4[name];
  58273. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58274. }
  58275. // Vector2
  58276. for (name in this._vectors2) {
  58277. this._effect.setVector2(name, this._vectors2[name]);
  58278. }
  58279. // Vector3
  58280. for (name in this._vectors3) {
  58281. this._effect.setVector3(name, this._vectors3[name]);
  58282. }
  58283. // Vector4
  58284. for (name in this._vectors4) {
  58285. this._effect.setVector4(name, this._vectors4[name]);
  58286. }
  58287. // Matrix
  58288. for (name in this._matrices) {
  58289. this._effect.setMatrix(name, this._matrices[name]);
  58290. }
  58291. // Matrix 3x3
  58292. for (name in this._matrices3x3) {
  58293. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58294. }
  58295. // Matrix 2x2
  58296. for (name in this._matrices2x2) {
  58297. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58298. }
  58299. // Vector2Array
  58300. for (name in this._vectors2Arrays) {
  58301. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58302. }
  58303. // Vector3Array
  58304. for (name in this._vectors3Arrays) {
  58305. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58306. }
  58307. }
  58308. this._afterBind(mesh);
  58309. };
  58310. ShaderMaterial.prototype.getActiveTextures = function () {
  58311. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58312. for (var name in this._textures) {
  58313. activeTextures.push(this._textures[name]);
  58314. }
  58315. for (var name in this._textureArrays) {
  58316. var array = this._textureArrays[name];
  58317. for (var index = 0; index < array.length; index++) {
  58318. activeTextures.push(array[index]);
  58319. }
  58320. }
  58321. return activeTextures;
  58322. };
  58323. ShaderMaterial.prototype.hasTexture = function (texture) {
  58324. if (_super.prototype.hasTexture.call(this, texture)) {
  58325. return true;
  58326. }
  58327. for (var name in this._textures) {
  58328. if (this._textures[name] === texture) {
  58329. return true;
  58330. }
  58331. }
  58332. for (var name in this._textureArrays) {
  58333. var array = this._textureArrays[name];
  58334. for (var index = 0; index < array.length; index++) {
  58335. if (array[index] === texture) {
  58336. return true;
  58337. }
  58338. }
  58339. }
  58340. return false;
  58341. };
  58342. ShaderMaterial.prototype.clone = function (name) {
  58343. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58344. return newShaderMaterial;
  58345. };
  58346. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58347. if (forceDisposeTextures) {
  58348. var name;
  58349. for (name in this._textures) {
  58350. this._textures[name].dispose();
  58351. }
  58352. for (name in this._textureArrays) {
  58353. var array = this._textureArrays[name];
  58354. for (var index = 0; index < array.length; index++) {
  58355. array[index].dispose();
  58356. }
  58357. }
  58358. }
  58359. this._textures = {};
  58360. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58361. };
  58362. ShaderMaterial.prototype.serialize = function () {
  58363. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58364. serializationObject.customType = "BABYLON.ShaderMaterial";
  58365. serializationObject.options = this._options;
  58366. serializationObject.shaderPath = this._shaderPath;
  58367. var name;
  58368. // Texture
  58369. serializationObject.textures = {};
  58370. for (name in this._textures) {
  58371. serializationObject.textures[name] = this._textures[name].serialize();
  58372. }
  58373. // Texture arrays
  58374. serializationObject.textureArrays = {};
  58375. for (name in this._textureArrays) {
  58376. serializationObject.textureArrays[name] = [];
  58377. var array = this._textureArrays[name];
  58378. for (var index = 0; index < array.length; index++) {
  58379. serializationObject.textureArrays[name].push(array[index].serialize());
  58380. }
  58381. }
  58382. // Float
  58383. serializationObject.floats = {};
  58384. for (name in this._floats) {
  58385. serializationObject.floats[name] = this._floats[name];
  58386. }
  58387. // Float s
  58388. serializationObject.FloatArrays = {};
  58389. for (name in this._floatsArrays) {
  58390. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58391. }
  58392. // Color3
  58393. serializationObject.colors3 = {};
  58394. for (name in this._colors3) {
  58395. serializationObject.colors3[name] = this._colors3[name].asArray();
  58396. }
  58397. // Color3 array
  58398. serializationObject.colors3Arrays = {};
  58399. for (name in this._colors3Arrays) {
  58400. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58401. }
  58402. // Color4
  58403. serializationObject.colors4 = {};
  58404. for (name in this._colors4) {
  58405. serializationObject.colors4[name] = this._colors4[name].asArray();
  58406. }
  58407. // Vector2
  58408. serializationObject.vectors2 = {};
  58409. for (name in this._vectors2) {
  58410. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58411. }
  58412. // Vector3
  58413. serializationObject.vectors3 = {};
  58414. for (name in this._vectors3) {
  58415. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58416. }
  58417. // Vector4
  58418. serializationObject.vectors4 = {};
  58419. for (name in this._vectors4) {
  58420. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58421. }
  58422. // Matrix
  58423. serializationObject.matrices = {};
  58424. for (name in this._matrices) {
  58425. serializationObject.matrices[name] = this._matrices[name].asArray();
  58426. }
  58427. // Matrix 3x3
  58428. serializationObject.matrices3x3 = {};
  58429. for (name in this._matrices3x3) {
  58430. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58431. }
  58432. // Matrix 2x2
  58433. serializationObject.matrices2x2 = {};
  58434. for (name in this._matrices2x2) {
  58435. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58436. }
  58437. // Vector2Array
  58438. serializationObject.vectors2Arrays = {};
  58439. for (name in this._vectors2Arrays) {
  58440. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58441. }
  58442. // Vector3Array
  58443. serializationObject.vectors3Arrays = {};
  58444. for (name in this._vectors3Arrays) {
  58445. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58446. }
  58447. return serializationObject;
  58448. };
  58449. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58450. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58451. var name;
  58452. // Texture
  58453. for (name in source.textures) {
  58454. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58455. }
  58456. // Texture arrays
  58457. for (name in source.textureArrays) {
  58458. var array = source.textureArrays[name];
  58459. var textureArray = new Array();
  58460. for (var index = 0; index < array.length; index++) {
  58461. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58462. }
  58463. material.setTextureArray(name, textureArray);
  58464. }
  58465. // Float
  58466. for (name in source.floats) {
  58467. material.setFloat(name, source.floats[name]);
  58468. }
  58469. // Float s
  58470. for (name in source.floatsArrays) {
  58471. material.setFloats(name, source.floatsArrays[name]);
  58472. }
  58473. // Color3
  58474. for (name in source.colors3) {
  58475. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58476. }
  58477. // Color3 arrays
  58478. for (name in source.colors3Arrays) {
  58479. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58480. if (i % 3 === 0) {
  58481. arr.push([num]);
  58482. }
  58483. else {
  58484. arr[arr.length - 1].push(num);
  58485. }
  58486. return arr;
  58487. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58488. material.setColor3Array(name, colors);
  58489. }
  58490. // Color4
  58491. for (name in source.colors4) {
  58492. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58493. }
  58494. // Vector2
  58495. for (name in source.vectors2) {
  58496. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58497. }
  58498. // Vector3
  58499. for (name in source.vectors3) {
  58500. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58501. }
  58502. // Vector4
  58503. for (name in source.vectors4) {
  58504. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58505. }
  58506. // Matrix
  58507. for (name in source.matrices) {
  58508. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58509. }
  58510. // Matrix 3x3
  58511. for (name in source.matrices3x3) {
  58512. material.setMatrix3x3(name, source.matrices3x3[name]);
  58513. }
  58514. // Matrix 2x2
  58515. for (name in source.matrices2x2) {
  58516. material.setMatrix2x2(name, source.matrices2x2[name]);
  58517. }
  58518. // Vector2Array
  58519. for (name in source.vectors2Arrays) {
  58520. material.setArray2(name, source.vectors2Arrays[name]);
  58521. }
  58522. // Vector3Array
  58523. for (name in source.vectors3Arrays) {
  58524. material.setArray3(name, source.vectors3Arrays[name]);
  58525. }
  58526. return material;
  58527. };
  58528. return ShaderMaterial;
  58529. }(BABYLON.Material));
  58530. BABYLON.ShaderMaterial = ShaderMaterial;
  58531. })(BABYLON || (BABYLON = {}));
  58532. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58533. var BABYLON;
  58534. (function (BABYLON) {
  58535. var GroundMesh = /** @class */ (function (_super) {
  58536. __extends(GroundMesh, _super);
  58537. function GroundMesh(name, scene) {
  58538. var _this = _super.call(this, name, scene) || this;
  58539. _this.generateOctree = false;
  58540. return _this;
  58541. }
  58542. GroundMesh.prototype.getClassName = function () {
  58543. return "GroundMesh";
  58544. };
  58545. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58546. get: function () {
  58547. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58548. },
  58549. enumerable: true,
  58550. configurable: true
  58551. });
  58552. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58553. get: function () {
  58554. return this._subdivisionsX;
  58555. },
  58556. enumerable: true,
  58557. configurable: true
  58558. });
  58559. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58560. get: function () {
  58561. return this._subdivisionsY;
  58562. },
  58563. enumerable: true,
  58564. configurable: true
  58565. });
  58566. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58567. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58568. this._subdivisionsX = chunksCount;
  58569. this._subdivisionsY = chunksCount;
  58570. this.subdivide(chunksCount);
  58571. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58572. };
  58573. /**
  58574. * Returns a height (y) value in the Worl system :
  58575. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58576. * Returns the ground y position if (x, z) are outside the ground surface.
  58577. */
  58578. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58579. var world = this.getWorldMatrix();
  58580. var invMat = BABYLON.Tmp.Matrix[5];
  58581. world.invertToRef(invMat);
  58582. var tmpVect = BABYLON.Tmp.Vector3[8];
  58583. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58584. x = tmpVect.x;
  58585. z = tmpVect.z;
  58586. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58587. return this.position.y;
  58588. }
  58589. if (!this._heightQuads || this._heightQuads.length == 0) {
  58590. this._initHeightQuads();
  58591. this._computeHeightQuads();
  58592. }
  58593. var facet = this._getFacetAt(x, z);
  58594. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58595. // return y in the World system
  58596. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58597. return tmpVect.y;
  58598. };
  58599. /**
  58600. * Returns a normalized vector (Vector3) orthogonal to the ground
  58601. * at the ground coordinates (x, z) expressed in the World system.
  58602. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58603. */
  58604. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58605. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58606. this.getNormalAtCoordinatesToRef(x, z, normal);
  58607. return normal;
  58608. };
  58609. /**
  58610. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58611. * at the ground coordinates (x, z) expressed in the World system.
  58612. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58613. * Returns the GroundMesh.
  58614. */
  58615. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58616. var world = this.getWorldMatrix();
  58617. var tmpMat = BABYLON.Tmp.Matrix[5];
  58618. world.invertToRef(tmpMat);
  58619. var tmpVect = BABYLON.Tmp.Vector3[8];
  58620. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58621. x = tmpVect.x;
  58622. z = tmpVect.z;
  58623. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58624. return this;
  58625. }
  58626. if (!this._heightQuads || this._heightQuads.length == 0) {
  58627. this._initHeightQuads();
  58628. this._computeHeightQuads();
  58629. }
  58630. var facet = this._getFacetAt(x, z);
  58631. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58632. return this;
  58633. };
  58634. /**
  58635. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58636. * if the ground has been updated.
  58637. * This can be used in the render loop.
  58638. * Returns the GroundMesh.
  58639. */
  58640. GroundMesh.prototype.updateCoordinateHeights = function () {
  58641. if (!this._heightQuads || this._heightQuads.length == 0) {
  58642. this._initHeightQuads();
  58643. }
  58644. this._computeHeightQuads();
  58645. return this;
  58646. };
  58647. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58648. GroundMesh.prototype._getFacetAt = function (x, z) {
  58649. // retrieve col and row from x, z coordinates in the ground local system
  58650. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58651. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58652. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58653. var facet;
  58654. if (z < quad.slope.x * x + quad.slope.y) {
  58655. facet = quad.facet1;
  58656. }
  58657. else {
  58658. facet = quad.facet2;
  58659. }
  58660. return facet;
  58661. };
  58662. // Creates and populates the heightMap array with "facet" elements :
  58663. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58664. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58665. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58666. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58667. // Returns the GroundMesh.
  58668. GroundMesh.prototype._initHeightQuads = function () {
  58669. var subdivisionsX = this._subdivisionsX;
  58670. var subdivisionsY = this._subdivisionsY;
  58671. this._heightQuads = new Array();
  58672. for (var row = 0; row < subdivisionsY; row++) {
  58673. for (var col = 0; col < subdivisionsX; col++) {
  58674. 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) };
  58675. this._heightQuads[row * subdivisionsX + col] = quad;
  58676. }
  58677. }
  58678. return this;
  58679. };
  58680. // Compute each quad element values and update the the heightMap array :
  58681. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58682. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58683. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58684. // Returns the GroundMesh.
  58685. GroundMesh.prototype._computeHeightQuads = function () {
  58686. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58687. if (!positions) {
  58688. return this;
  58689. }
  58690. var v1 = BABYLON.Tmp.Vector3[3];
  58691. var v2 = BABYLON.Tmp.Vector3[2];
  58692. var v3 = BABYLON.Tmp.Vector3[1];
  58693. var v4 = BABYLON.Tmp.Vector3[0];
  58694. var v1v2 = BABYLON.Tmp.Vector3[4];
  58695. var v1v3 = BABYLON.Tmp.Vector3[5];
  58696. var v1v4 = BABYLON.Tmp.Vector3[6];
  58697. var norm1 = BABYLON.Tmp.Vector3[7];
  58698. var norm2 = BABYLON.Tmp.Vector3[8];
  58699. var i = 0;
  58700. var j = 0;
  58701. var k = 0;
  58702. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58703. var h = 0;
  58704. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58705. var d2 = 0;
  58706. var subdivisionsX = this._subdivisionsX;
  58707. var subdivisionsY = this._subdivisionsY;
  58708. for (var row = 0; row < subdivisionsY; row++) {
  58709. for (var col = 0; col < subdivisionsX; col++) {
  58710. i = col * 3;
  58711. j = row * (subdivisionsX + 1) * 3;
  58712. k = (row + 1) * (subdivisionsX + 1) * 3;
  58713. v1.x = positions[j + i];
  58714. v1.y = positions[j + i + 1];
  58715. v1.z = positions[j + i + 2];
  58716. v2.x = positions[j + i + 3];
  58717. v2.y = positions[j + i + 4];
  58718. v2.z = positions[j + i + 5];
  58719. v3.x = positions[k + i];
  58720. v3.y = positions[k + i + 1];
  58721. v3.z = positions[k + i + 2];
  58722. v4.x = positions[k + i + 3];
  58723. v4.y = positions[k + i + 4];
  58724. v4.z = positions[k + i + 5];
  58725. // 2D slope V1V4
  58726. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58727. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58728. // facet equations :
  58729. // we compute each facet normal vector
  58730. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58731. // we compute the value d by applying the equation to v1 which belongs to the plane
  58732. // then we store the facet equation in a Vector4
  58733. v2.subtractToRef(v1, v1v2);
  58734. v3.subtractToRef(v1, v1v3);
  58735. v4.subtractToRef(v1, v1v4);
  58736. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58737. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58738. norm1.normalize();
  58739. norm2.normalize();
  58740. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58741. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58742. var quad = this._heightQuads[row * subdivisionsX + col];
  58743. quad.slope.copyFromFloats(cd, h);
  58744. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58745. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58746. }
  58747. }
  58748. return this;
  58749. };
  58750. GroundMesh.prototype.serialize = function (serializationObject) {
  58751. _super.prototype.serialize.call(this, serializationObject);
  58752. serializationObject.subdivisionsX = this._subdivisionsX;
  58753. serializationObject.subdivisionsY = this._subdivisionsY;
  58754. serializationObject.minX = this._minX;
  58755. serializationObject.maxX = this._maxX;
  58756. serializationObject.minZ = this._minZ;
  58757. serializationObject.maxZ = this._maxZ;
  58758. serializationObject.width = this._width;
  58759. serializationObject.height = this._height;
  58760. };
  58761. GroundMesh.Parse = function (parsedMesh, scene) {
  58762. var result = new GroundMesh(parsedMesh.name, scene);
  58763. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58764. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58765. result._minX = parsedMesh.minX;
  58766. result._maxX = parsedMesh.maxX;
  58767. result._minZ = parsedMesh.minZ;
  58768. result._maxZ = parsedMesh.maxZ;
  58769. result._width = parsedMesh.width;
  58770. result._height = parsedMesh.height;
  58771. return result;
  58772. };
  58773. return GroundMesh;
  58774. }(BABYLON.Mesh));
  58775. BABYLON.GroundMesh = GroundMesh;
  58776. })(BABYLON || (BABYLON = {}));
  58777. //# sourceMappingURL=babylon.groundMesh.js.map
  58778. var BABYLON;
  58779. (function (BABYLON) {
  58780. /**
  58781. * Creates an instance based on a source mesh.
  58782. */
  58783. var InstancedMesh = /** @class */ (function (_super) {
  58784. __extends(InstancedMesh, _super);
  58785. function InstancedMesh(name, source) {
  58786. var _this = _super.call(this, name, source.getScene()) || this;
  58787. source.instances.push(_this);
  58788. _this._sourceMesh = source;
  58789. _this.position.copyFrom(source.position);
  58790. _this.rotation.copyFrom(source.rotation);
  58791. _this.scaling.copyFrom(source.scaling);
  58792. if (source.rotationQuaternion) {
  58793. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58794. }
  58795. _this.infiniteDistance = source.infiniteDistance;
  58796. _this.setPivotMatrix(source.getPivotMatrix());
  58797. _this.refreshBoundingInfo();
  58798. _this._syncSubMeshes();
  58799. return _this;
  58800. }
  58801. /**
  58802. * Returns the string "InstancedMesh".
  58803. */
  58804. InstancedMesh.prototype.getClassName = function () {
  58805. return "InstancedMesh";
  58806. };
  58807. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58808. // Methods
  58809. get: function () {
  58810. return this._sourceMesh.receiveShadows;
  58811. },
  58812. enumerable: true,
  58813. configurable: true
  58814. });
  58815. Object.defineProperty(InstancedMesh.prototype, "material", {
  58816. get: function () {
  58817. return this._sourceMesh.material;
  58818. },
  58819. enumerable: true,
  58820. configurable: true
  58821. });
  58822. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58823. get: function () {
  58824. return this._sourceMesh.visibility;
  58825. },
  58826. enumerable: true,
  58827. configurable: true
  58828. });
  58829. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58830. get: function () {
  58831. return this._sourceMesh.skeleton;
  58832. },
  58833. enumerable: true,
  58834. configurable: true
  58835. });
  58836. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58837. get: function () {
  58838. return this._sourceMesh.renderingGroupId;
  58839. },
  58840. set: function (value) {
  58841. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58842. return;
  58843. }
  58844. //no-op with warning
  58845. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58846. },
  58847. enumerable: true,
  58848. configurable: true
  58849. });
  58850. /**
  58851. * Returns the total number of vertices (integer).
  58852. */
  58853. InstancedMesh.prototype.getTotalVertices = function () {
  58854. return this._sourceMesh.getTotalVertices();
  58855. };
  58856. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58857. get: function () {
  58858. return this._sourceMesh;
  58859. },
  58860. enumerable: true,
  58861. configurable: true
  58862. });
  58863. /**
  58864. * Is this node ready to be used/rendered
  58865. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58866. * @return {boolean} is it ready
  58867. */
  58868. InstancedMesh.prototype.isReady = function (completeCheck) {
  58869. if (completeCheck === void 0) { completeCheck = false; }
  58870. return this._sourceMesh.isReady(completeCheck, true);
  58871. };
  58872. /**
  58873. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58874. */
  58875. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58876. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58877. };
  58878. /**
  58879. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58880. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58881. * The `data` are either a numeric array either a Float32Array.
  58882. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58883. * 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).
  58884. * Note that a new underlying VertexBuffer object is created each call.
  58885. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58886. *
  58887. * Possible `kind` values :
  58888. * - BABYLON.VertexBuffer.PositionKind
  58889. * - BABYLON.VertexBuffer.UVKind
  58890. * - BABYLON.VertexBuffer.UV2Kind
  58891. * - BABYLON.VertexBuffer.UV3Kind
  58892. * - BABYLON.VertexBuffer.UV4Kind
  58893. * - BABYLON.VertexBuffer.UV5Kind
  58894. * - BABYLON.VertexBuffer.UV6Kind
  58895. * - BABYLON.VertexBuffer.ColorKind
  58896. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58897. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58898. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58899. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58900. *
  58901. * Returns the Mesh.
  58902. */
  58903. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58904. if (this.sourceMesh) {
  58905. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58906. }
  58907. return this.sourceMesh;
  58908. };
  58909. /**
  58910. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58911. * If the mesh has no geometry, it is simply returned as it is.
  58912. * The `data` are either a numeric array either a Float32Array.
  58913. * No new underlying VertexBuffer object is created.
  58914. * 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.
  58915. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58916. *
  58917. * Possible `kind` values :
  58918. * - BABYLON.VertexBuffer.PositionKind
  58919. * - BABYLON.VertexBuffer.UVKind
  58920. * - BABYLON.VertexBuffer.UV2Kind
  58921. * - BABYLON.VertexBuffer.UV3Kind
  58922. * - BABYLON.VertexBuffer.UV4Kind
  58923. * - BABYLON.VertexBuffer.UV5Kind
  58924. * - BABYLON.VertexBuffer.UV6Kind
  58925. * - BABYLON.VertexBuffer.ColorKind
  58926. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58927. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58928. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58929. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58930. *
  58931. * Returns the Mesh.
  58932. */
  58933. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58934. if (this.sourceMesh) {
  58935. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58936. }
  58937. return this.sourceMesh;
  58938. };
  58939. /**
  58940. * Sets the mesh indices.
  58941. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58942. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58943. * This method creates a new index buffer each call.
  58944. * Returns the Mesh.
  58945. */
  58946. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58947. if (totalVertices === void 0) { totalVertices = null; }
  58948. if (this.sourceMesh) {
  58949. this.sourceMesh.setIndices(indices, totalVertices);
  58950. }
  58951. return this.sourceMesh;
  58952. };
  58953. /**
  58954. * Boolean : True if the mesh owns the requested kind of data.
  58955. */
  58956. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58957. return this._sourceMesh.isVerticesDataPresent(kind);
  58958. };
  58959. /**
  58960. * Returns an array of indices (IndicesArray).
  58961. */
  58962. InstancedMesh.prototype.getIndices = function () {
  58963. return this._sourceMesh.getIndices();
  58964. };
  58965. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58966. get: function () {
  58967. return this._sourceMesh._positions;
  58968. },
  58969. enumerable: true,
  58970. configurable: true
  58971. });
  58972. /**
  58973. * Sets a new updated BoundingInfo to the mesh.
  58974. * Returns the mesh.
  58975. */
  58976. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58977. var meshBB = this._sourceMesh.getBoundingInfo();
  58978. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58979. this._updateBoundingInfo();
  58980. return this;
  58981. };
  58982. /** @hidden */
  58983. InstancedMesh.prototype._preActivate = function () {
  58984. if (this._currentLOD) {
  58985. this._currentLOD._preActivate();
  58986. }
  58987. return this;
  58988. };
  58989. /** @hidden */
  58990. InstancedMesh.prototype._activate = function (renderId) {
  58991. if (this._currentLOD) {
  58992. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58993. }
  58994. return this;
  58995. };
  58996. /**
  58997. * Returns the current associated LOD AbstractMesh.
  58998. */
  58999. InstancedMesh.prototype.getLOD = function (camera) {
  59000. if (!camera) {
  59001. return this;
  59002. }
  59003. var boundingInfo = this.getBoundingInfo();
  59004. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59005. if (this._currentLOD === this.sourceMesh) {
  59006. return this;
  59007. }
  59008. return this._currentLOD;
  59009. };
  59010. /** @hidden */
  59011. InstancedMesh.prototype._syncSubMeshes = function () {
  59012. this.releaseSubMeshes();
  59013. if (this._sourceMesh.subMeshes) {
  59014. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59015. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59016. }
  59017. }
  59018. return this;
  59019. };
  59020. /** @hidden */
  59021. InstancedMesh.prototype._generatePointsArray = function () {
  59022. return this._sourceMesh._generatePointsArray();
  59023. };
  59024. /**
  59025. * Creates a new InstancedMesh from the current mesh.
  59026. * - name (string) : the cloned mesh name
  59027. * - newParent (optional Node) : the optional Node to parent the clone to.
  59028. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59029. *
  59030. * Returns the clone.
  59031. */
  59032. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59033. var result = this._sourceMesh.createInstance(name);
  59034. // Deep copy
  59035. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59036. // Bounding info
  59037. this.refreshBoundingInfo();
  59038. // Parent
  59039. if (newParent) {
  59040. result.parent = newParent;
  59041. }
  59042. if (!doNotCloneChildren) {
  59043. // Children
  59044. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59045. var mesh = this.getScene().meshes[index];
  59046. if (mesh.parent === this) {
  59047. mesh.clone(mesh.name, result);
  59048. }
  59049. }
  59050. }
  59051. result.computeWorldMatrix(true);
  59052. return result;
  59053. };
  59054. /**
  59055. * Disposes the InstancedMesh.
  59056. * Returns nothing.
  59057. */
  59058. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59059. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59060. // Remove from mesh
  59061. var index = this._sourceMesh.instances.indexOf(this);
  59062. this._sourceMesh.instances.splice(index, 1);
  59063. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59064. };
  59065. return InstancedMesh;
  59066. }(BABYLON.AbstractMesh));
  59067. BABYLON.InstancedMesh = InstancedMesh;
  59068. })(BABYLON || (BABYLON = {}));
  59069. //# sourceMappingURL=babylon.instancedMesh.js.map
  59070. var BABYLON;
  59071. (function (BABYLON) {
  59072. var LinesMesh = /** @class */ (function (_super) {
  59073. __extends(LinesMesh, _super);
  59074. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59075. if (scene === void 0) { scene = null; }
  59076. if (parent === void 0) { parent = null; }
  59077. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59078. _this.useVertexColor = useVertexColor;
  59079. _this.useVertexAlpha = useVertexAlpha;
  59080. _this.color = new BABYLON.Color3(1, 1, 1);
  59081. _this.alpha = 1;
  59082. if (source) {
  59083. _this.color = source.color.clone();
  59084. _this.alpha = source.alpha;
  59085. _this.useVertexColor = source.useVertexColor;
  59086. _this.useVertexAlpha = source.useVertexAlpha;
  59087. }
  59088. _this._intersectionThreshold = 0.1;
  59089. var defines = [];
  59090. var options = {
  59091. attributes: [BABYLON.VertexBuffer.PositionKind],
  59092. uniforms: ["world", "viewProjection"],
  59093. needAlphaBlending: true,
  59094. defines: defines
  59095. };
  59096. if (useVertexAlpha === false) {
  59097. options.needAlphaBlending = false;
  59098. }
  59099. if (!useVertexColor) {
  59100. options.uniforms.push("color");
  59101. }
  59102. else {
  59103. options.defines.push("#define VERTEXCOLOR");
  59104. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59105. }
  59106. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59107. return _this;
  59108. }
  59109. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59110. /**
  59111. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59112. * This margin is expressed in world space coordinates, so its value may vary.
  59113. * Default value is 0.1
  59114. * @returns the intersection Threshold value.
  59115. */
  59116. get: function () {
  59117. return this._intersectionThreshold;
  59118. },
  59119. /**
  59120. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59121. * This margin is expressed in world space coordinates, so its value may vary.
  59122. * @param value the new threshold to apply
  59123. */
  59124. set: function (value) {
  59125. if (this._intersectionThreshold === value) {
  59126. return;
  59127. }
  59128. this._intersectionThreshold = value;
  59129. if (this.geometry) {
  59130. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59131. }
  59132. },
  59133. enumerable: true,
  59134. configurable: true
  59135. });
  59136. /**
  59137. * Returns the string "LineMesh"
  59138. */
  59139. LinesMesh.prototype.getClassName = function () {
  59140. return "LinesMesh";
  59141. };
  59142. Object.defineProperty(LinesMesh.prototype, "material", {
  59143. /**
  59144. * @hidden
  59145. */
  59146. get: function () {
  59147. return this._colorShader;
  59148. },
  59149. /**
  59150. * @hidden
  59151. */
  59152. set: function (value) {
  59153. // Do nothing
  59154. },
  59155. enumerable: true,
  59156. configurable: true
  59157. });
  59158. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59159. /**
  59160. * @hidden
  59161. */
  59162. get: function () {
  59163. return false;
  59164. },
  59165. enumerable: true,
  59166. configurable: true
  59167. });
  59168. LinesMesh.prototype.createInstance = function (name) {
  59169. throw new Error("LinesMeshes do not support createInstance.");
  59170. };
  59171. /** @hidden */
  59172. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59173. if (!this._geometry) {
  59174. return this;
  59175. }
  59176. // VBOs
  59177. this._geometry._bind(this._colorShader.getEffect());
  59178. // Color
  59179. if (!this.useVertexColor) {
  59180. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59181. }
  59182. return this;
  59183. };
  59184. /** @hidden */
  59185. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59186. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59187. return this;
  59188. }
  59189. var engine = this.getScene().getEngine();
  59190. // Draw order
  59191. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59192. return this;
  59193. };
  59194. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59195. this._colorShader.dispose();
  59196. _super.prototype.dispose.call(this, doNotRecurse);
  59197. };
  59198. /**
  59199. * Returns a new LineMesh object cloned from the current one.
  59200. */
  59201. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59202. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59203. };
  59204. return LinesMesh;
  59205. }(BABYLON.Mesh));
  59206. BABYLON.LinesMesh = LinesMesh;
  59207. })(BABYLON || (BABYLON = {}));
  59208. //# sourceMappingURL=babylon.linesMesh.js.map
  59209. var BABYLON;
  59210. (function (BABYLON) {
  59211. /**
  59212. * This class implement a typical dictionary using a string as key and the generic type T as value.
  59213. * The underlying implementation relies on an associative array to ensure the best performances.
  59214. * The value can be anything including 'null' but except 'undefined'
  59215. */
  59216. var StringDictionary = /** @class */ (function () {
  59217. function StringDictionary() {
  59218. this._count = 0;
  59219. this._data = {};
  59220. }
  59221. /**
  59222. * This will clear this dictionary and copy the content from the 'source' one.
  59223. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  59224. * @param source the dictionary to take the content from and copy to this dictionary
  59225. */
  59226. StringDictionary.prototype.copyFrom = function (source) {
  59227. var _this = this;
  59228. this.clear();
  59229. source.forEach(function (t, v) { return _this.add(t, v); });
  59230. };
  59231. /**
  59232. * Get a value based from its key
  59233. * @param key the given key to get the matching value from
  59234. * @return the value if found, otherwise undefined is returned
  59235. */
  59236. StringDictionary.prototype.get = function (key) {
  59237. var val = this._data[key];
  59238. if (val !== undefined) {
  59239. return val;
  59240. }
  59241. return undefined;
  59242. };
  59243. /**
  59244. * Get a value from its key or add it if it doesn't exist.
  59245. * This method will ensure you that a given key/data will be present in the dictionary.
  59246. * @param key the given key to get the matching value from
  59247. * @param factory the factory that will create the value if the key is not present in the dictionary.
  59248. * The factory will only be invoked if there's no data for the given key.
  59249. * @return the value corresponding to the key.
  59250. */
  59251. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  59252. var val = this.get(key);
  59253. if (val !== undefined) {
  59254. return val;
  59255. }
  59256. val = factory(key);
  59257. if (val) {
  59258. this.add(key, val);
  59259. }
  59260. return val;
  59261. };
  59262. /**
  59263. * Get a value from its key if present in the dictionary otherwise add it
  59264. * @param key the key to get the value from
  59265. * @param val if there's no such key/value pair in the dictionary add it with this value
  59266. * @return the value corresponding to the key
  59267. */
  59268. StringDictionary.prototype.getOrAdd = function (key, val) {
  59269. var curVal = this.get(key);
  59270. if (curVal !== undefined) {
  59271. return curVal;
  59272. }
  59273. this.add(key, val);
  59274. return val;
  59275. };
  59276. /**
  59277. * Check if there's a given key in the dictionary
  59278. * @param key the key to check for
  59279. * @return true if the key is present, false otherwise
  59280. */
  59281. StringDictionary.prototype.contains = function (key) {
  59282. return this._data[key] !== undefined;
  59283. };
  59284. /**
  59285. * Add a new key and its corresponding value
  59286. * @param key the key to add
  59287. * @param value the value corresponding to the key
  59288. * @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
  59289. */
  59290. StringDictionary.prototype.add = function (key, value) {
  59291. if (this._data[key] !== undefined) {
  59292. return false;
  59293. }
  59294. this._data[key] = value;
  59295. ++this._count;
  59296. return true;
  59297. };
  59298. StringDictionary.prototype.set = function (key, value) {
  59299. if (this._data[key] === undefined) {
  59300. return false;
  59301. }
  59302. this._data[key] = value;
  59303. return true;
  59304. };
  59305. /**
  59306. * Get the element of the given key and remove it from the dictionary
  59307. * @param key
  59308. */
  59309. StringDictionary.prototype.getAndRemove = function (key) {
  59310. var val = this.get(key);
  59311. if (val !== undefined) {
  59312. delete this._data[key];
  59313. --this._count;
  59314. return val;
  59315. }
  59316. return null;
  59317. };
  59318. /**
  59319. * Remove a key/value from the dictionary.
  59320. * @param key the key to remove
  59321. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59322. */
  59323. StringDictionary.prototype.remove = function (key) {
  59324. if (this.contains(key)) {
  59325. delete this._data[key];
  59326. --this._count;
  59327. return true;
  59328. }
  59329. return false;
  59330. };
  59331. /**
  59332. * Clear the whole content of the dictionary
  59333. */
  59334. StringDictionary.prototype.clear = function () {
  59335. this._data = {};
  59336. this._count = 0;
  59337. };
  59338. Object.defineProperty(StringDictionary.prototype, "count", {
  59339. get: function () {
  59340. return this._count;
  59341. },
  59342. enumerable: true,
  59343. configurable: true
  59344. });
  59345. /**
  59346. * Execute a callback on each key/val of the dictionary.
  59347. * Note that you can remove any element in this dictionary in the callback implementation
  59348. * @param callback the callback to execute on a given key/value pair
  59349. */
  59350. StringDictionary.prototype.forEach = function (callback) {
  59351. for (var cur in this._data) {
  59352. var val = this._data[cur];
  59353. callback(cur, val);
  59354. }
  59355. };
  59356. /**
  59357. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59358. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59359. * Note that you can remove any element in this dictionary in the callback implementation
  59360. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59361. */
  59362. StringDictionary.prototype.first = function (callback) {
  59363. for (var cur in this._data) {
  59364. var val = this._data[cur];
  59365. var res = callback(cur, val);
  59366. if (res) {
  59367. return res;
  59368. }
  59369. }
  59370. return null;
  59371. };
  59372. return StringDictionary;
  59373. }());
  59374. BABYLON.StringDictionary = StringDictionary;
  59375. })(BABYLON || (BABYLON = {}));
  59376. //# sourceMappingURL=babylon.stringDictionary.js.map
  59377. var BABYLON;
  59378. (function (BABYLON) {
  59379. var Debug;
  59380. (function (Debug) {
  59381. /**
  59382. * Class used to render a debug view of a given skeleton
  59383. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  59384. */
  59385. var SkeletonViewer = /** @class */ (function () {
  59386. /**
  59387. * Creates a new SkeletonViewer
  59388. * @param skeleton defines the skeleton to render
  59389. * @param mesh defines the mesh attached to the skeleton
  59390. * @param scene defines the hosting scene
  59391. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  59392. * @param renderingGroupId defines the rendering group id to use with the viewer
  59393. */
  59394. function SkeletonViewer(
  59395. /** defines the skeleton to render */
  59396. skeleton,
  59397. /** defines the mesh attached to the skeleton */
  59398. mesh, scene,
  59399. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  59400. autoUpdateBonesMatrices,
  59401. /** defines the rendering group id to use with the viewer */
  59402. renderingGroupId) {
  59403. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59404. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59405. this.skeleton = skeleton;
  59406. this.mesh = mesh;
  59407. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59408. this.renderingGroupId = renderingGroupId;
  59409. /** Gets or sets the color used to render the skeleton */
  59410. this.color = BABYLON.Color3.White();
  59411. this._debugLines = new Array();
  59412. this._isEnabled = false;
  59413. this._scene = scene;
  59414. this.update();
  59415. this._renderFunction = this.update.bind(this);
  59416. }
  59417. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59418. get: function () {
  59419. return this._isEnabled;
  59420. },
  59421. /** Gets or sets a boolean indicating if the viewer is enabled */
  59422. set: function (value) {
  59423. if (this._isEnabled === value) {
  59424. return;
  59425. }
  59426. this._isEnabled = value;
  59427. if (value) {
  59428. this._scene.registerBeforeRender(this._renderFunction);
  59429. }
  59430. else {
  59431. this._scene.unregisterBeforeRender(this._renderFunction);
  59432. }
  59433. },
  59434. enumerable: true,
  59435. configurable: true
  59436. });
  59437. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59438. if (x === void 0) { x = 0; }
  59439. if (y === void 0) { y = 0; }
  59440. if (z === void 0) { z = 0; }
  59441. var tmat = BABYLON.Tmp.Matrix[0];
  59442. var parentBone = bone.getParent();
  59443. tmat.copyFrom(bone.getLocalMatrix());
  59444. if (x !== 0 || y !== 0 || z !== 0) {
  59445. var tmat2 = BABYLON.Tmp.Matrix[1];
  59446. BABYLON.Matrix.IdentityToRef(tmat2);
  59447. tmat2.m[12] = x;
  59448. tmat2.m[13] = y;
  59449. tmat2.m[14] = z;
  59450. tmat2.multiplyToRef(tmat, tmat);
  59451. }
  59452. if (parentBone) {
  59453. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59454. }
  59455. tmat.multiplyToRef(meshMat, tmat);
  59456. position.x = tmat.m[12];
  59457. position.y = tmat.m[13];
  59458. position.z = tmat.m[14];
  59459. };
  59460. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59461. var len = bones.length;
  59462. var meshPos = this.mesh.position;
  59463. for (var i = 0; i < len; i++) {
  59464. var bone = bones[i];
  59465. var points = this._debugLines[i];
  59466. if (!points) {
  59467. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59468. this._debugLines[i] = points;
  59469. }
  59470. this._getBonePosition(points[0], bone, meshMat);
  59471. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59472. points[0].subtractInPlace(meshPos);
  59473. points[1].subtractInPlace(meshPos);
  59474. }
  59475. };
  59476. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59477. var len = bones.length;
  59478. var boneNum = 0;
  59479. var meshPos = this.mesh.position;
  59480. for (var i = len - 1; i >= 0; i--) {
  59481. var childBone = bones[i];
  59482. var parentBone = childBone.getParent();
  59483. if (!parentBone) {
  59484. continue;
  59485. }
  59486. var points = this._debugLines[boneNum];
  59487. if (!points) {
  59488. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59489. this._debugLines[boneNum] = points;
  59490. }
  59491. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59492. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59493. points[0].subtractInPlace(meshPos);
  59494. points[1].subtractInPlace(meshPos);
  59495. boneNum++;
  59496. }
  59497. };
  59498. /** Update the viewer to sync with current skeleton state */
  59499. SkeletonViewer.prototype.update = function () {
  59500. if (this.autoUpdateBonesMatrices) {
  59501. this.skeleton.computeAbsoluteTransforms();
  59502. }
  59503. if (this.skeleton.bones[0].length === undefined) {
  59504. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59505. }
  59506. else {
  59507. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59508. }
  59509. if (!this._debugMesh) {
  59510. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  59511. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59512. }
  59513. else {
  59514. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59515. }
  59516. this._debugMesh.position.copyFrom(this.mesh.position);
  59517. this._debugMesh.color = this.color;
  59518. };
  59519. /** Release associated resources */
  59520. SkeletonViewer.prototype.dispose = function () {
  59521. if (this._debugMesh) {
  59522. this.isEnabled = false;
  59523. this._debugMesh.dispose();
  59524. this._debugMesh = null;
  59525. }
  59526. };
  59527. return SkeletonViewer;
  59528. }());
  59529. Debug.SkeletonViewer = SkeletonViewer;
  59530. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59531. })(BABYLON || (BABYLON = {}));
  59532. //# sourceMappingURL=babylon.skeletonViewer.js.map
  59533. /**
  59534. * Module Debug contains the (visual) components to debug a scene correctly
  59535. */
  59536. var BABYLON;
  59537. (function (BABYLON) {
  59538. var Debug;
  59539. (function (Debug) {
  59540. /**
  59541. * The Axes viewer will show 3 axes in a specific point in space
  59542. */
  59543. var AxesViewer = /** @class */ (function () {
  59544. /**
  59545. * Creates a new AxesViewer
  59546. * @param scene defines the hosting scene
  59547. * @param scaleLines defines a number used to scale line length (1 by default)
  59548. */
  59549. function AxesViewer(scene, scaleLines) {
  59550. if (scaleLines === void 0) { scaleLines = 1; }
  59551. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59552. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59553. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59554. /**
  59555. * Gets or sets a number used to scale line length
  59556. */
  59557. this.scaleLines = 1;
  59558. this.scaleLines = scaleLines;
  59559. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59560. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59561. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59562. this._xmesh.renderingGroupId = 2;
  59563. this._ymesh.renderingGroupId = 2;
  59564. this._zmesh.renderingGroupId = 2;
  59565. this._xmesh.material.checkReadyOnlyOnce = true;
  59566. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  59567. this._ymesh.material.checkReadyOnlyOnce = true;
  59568. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  59569. this._zmesh.material.checkReadyOnlyOnce = true;
  59570. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  59571. this.scene = scene;
  59572. }
  59573. /**
  59574. * Force the viewer to update
  59575. * @param position defines the position of the viewer
  59576. * @param xaxis defines the x axis of the viewer
  59577. * @param yaxis defines the y axis of the viewer
  59578. * @param zaxis defines the z axis of the viewer
  59579. */
  59580. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  59581. var scaleLines = this.scaleLines;
  59582. if (this._xmesh) {
  59583. this._xmesh.position.copyFrom(position);
  59584. }
  59585. if (this._ymesh) {
  59586. this._ymesh.position.copyFrom(position);
  59587. }
  59588. if (this._zmesh) {
  59589. this._zmesh.position.copyFrom(position);
  59590. }
  59591. var point2 = this._xline[1];
  59592. point2.x = xaxis.x * scaleLines;
  59593. point2.y = xaxis.y * scaleLines;
  59594. point2.z = xaxis.z * scaleLines;
  59595. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  59596. point2 = this._yline[1];
  59597. point2.x = yaxis.x * scaleLines;
  59598. point2.y = yaxis.y * scaleLines;
  59599. point2.z = yaxis.z * scaleLines;
  59600. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  59601. point2 = this._zline[1];
  59602. point2.x = zaxis.x * scaleLines;
  59603. point2.y = zaxis.y * scaleLines;
  59604. point2.z = zaxis.z * scaleLines;
  59605. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  59606. };
  59607. /** Releases resources */
  59608. AxesViewer.prototype.dispose = function () {
  59609. if (this._xmesh) {
  59610. this._xmesh.dispose();
  59611. }
  59612. if (this._ymesh) {
  59613. this._ymesh.dispose();
  59614. }
  59615. if (this._zmesh) {
  59616. this._zmesh.dispose();
  59617. }
  59618. this._xmesh = null;
  59619. this._ymesh = null;
  59620. this._zmesh = null;
  59621. this.scene = null;
  59622. };
  59623. return AxesViewer;
  59624. }());
  59625. Debug.AxesViewer = AxesViewer;
  59626. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59627. })(BABYLON || (BABYLON = {}));
  59628. //# sourceMappingURL=babylon.axesViewer.js.map
  59629. var BABYLON;
  59630. (function (BABYLON) {
  59631. var Debug;
  59632. (function (Debug) {
  59633. /**
  59634. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  59635. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  59636. */
  59637. var BoneAxesViewer = /** @class */ (function (_super) {
  59638. __extends(BoneAxesViewer, _super);
  59639. /**
  59640. * Creates a new BoneAxesViewer
  59641. * @param scene defines the hosting scene
  59642. * @param bone defines the target bone
  59643. * @param mesh defines the target mesh
  59644. * @param scaleLines defines a scaling factor for line length (1 by default)
  59645. */
  59646. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  59647. if (scaleLines === void 0) { scaleLines = 1; }
  59648. var _this = _super.call(this, scene, scaleLines) || this;
  59649. /** Gets current position */
  59650. _this.pos = BABYLON.Vector3.Zero();
  59651. /** Gets direction of X axis */
  59652. _this.xaxis = BABYLON.Vector3.Zero();
  59653. /** Gets direction of Y axis */
  59654. _this.yaxis = BABYLON.Vector3.Zero();
  59655. /** Gets direction of Z axis */
  59656. _this.zaxis = BABYLON.Vector3.Zero();
  59657. _this.mesh = mesh;
  59658. _this.bone = bone;
  59659. return _this;
  59660. }
  59661. /**
  59662. * Force the viewer to update
  59663. */
  59664. BoneAxesViewer.prototype.update = function () {
  59665. if (!this.mesh || !this.bone) {
  59666. return;
  59667. }
  59668. var bone = this.bone;
  59669. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  59670. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  59671. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  59672. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  59673. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  59674. };
  59675. /** Releases resources */
  59676. BoneAxesViewer.prototype.dispose = function () {
  59677. if (this.mesh) {
  59678. this.mesh = null;
  59679. this.bone = null;
  59680. _super.prototype.dispose.call(this);
  59681. }
  59682. };
  59683. return BoneAxesViewer;
  59684. }(Debug.AxesViewer));
  59685. Debug.BoneAxesViewer = BoneAxesViewer;
  59686. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59687. })(BABYLON || (BABYLON = {}));
  59688. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  59689. var BABYLON;
  59690. (function (BABYLON) {
  59691. var RayHelper = /** @class */ (function () {
  59692. function RayHelper(ray) {
  59693. this.ray = ray;
  59694. }
  59695. RayHelper.CreateAndShow = function (ray, scene, color) {
  59696. var helper = new RayHelper(ray);
  59697. helper.show(scene, color);
  59698. return helper;
  59699. };
  59700. RayHelper.prototype.show = function (scene, color) {
  59701. if (!this._renderFunction && this.ray) {
  59702. var ray = this.ray;
  59703. this._renderFunction = this._render.bind(this);
  59704. this._scene = scene;
  59705. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  59706. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  59707. if (this._renderFunction) {
  59708. this._scene.registerBeforeRender(this._renderFunction);
  59709. }
  59710. }
  59711. if (color && this._renderLine) {
  59712. this._renderLine.color.copyFrom(color);
  59713. }
  59714. };
  59715. RayHelper.prototype.hide = function () {
  59716. if (this._renderFunction && this._scene) {
  59717. this._scene.unregisterBeforeRender(this._renderFunction);
  59718. this._scene = null;
  59719. this._renderFunction = null;
  59720. if (this._renderLine) {
  59721. this._renderLine.dispose();
  59722. this._renderLine = null;
  59723. }
  59724. this._renderPoints = [];
  59725. }
  59726. };
  59727. RayHelper.prototype._render = function () {
  59728. var ray = this.ray;
  59729. if (!ray) {
  59730. return;
  59731. }
  59732. var point = this._renderPoints[1];
  59733. var len = Math.min(ray.length, 1000000);
  59734. point.copyFrom(ray.direction);
  59735. point.scaleInPlace(len);
  59736. point.addInPlace(ray.origin);
  59737. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  59738. };
  59739. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  59740. this._attachedToMesh = mesh;
  59741. var ray = this.ray;
  59742. if (!ray) {
  59743. return;
  59744. }
  59745. if (!ray.direction) {
  59746. ray.direction = BABYLON.Vector3.Zero();
  59747. }
  59748. if (!ray.origin) {
  59749. ray.origin = BABYLON.Vector3.Zero();
  59750. }
  59751. if (length) {
  59752. ray.length = length;
  59753. }
  59754. if (!meshSpaceOrigin) {
  59755. meshSpaceOrigin = BABYLON.Vector3.Zero();
  59756. }
  59757. if (!meshSpaceDirection) {
  59758. // -1 so that this will work with Mesh.lookAt
  59759. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  59760. }
  59761. if (!this._meshSpaceDirection) {
  59762. this._meshSpaceDirection = meshSpaceDirection.clone();
  59763. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  59764. }
  59765. else {
  59766. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  59767. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  59768. }
  59769. if (!this._updateToMeshFunction) {
  59770. this._updateToMeshFunction = this._updateToMesh.bind(this);
  59771. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  59772. }
  59773. this._updateToMesh();
  59774. };
  59775. RayHelper.prototype.detachFromMesh = function () {
  59776. if (this._attachedToMesh) {
  59777. if (this._updateToMeshFunction) {
  59778. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  59779. }
  59780. this._attachedToMesh = null;
  59781. this._updateToMeshFunction = null;
  59782. }
  59783. };
  59784. RayHelper.prototype._updateToMesh = function () {
  59785. var ray = this.ray;
  59786. if (!this._attachedToMesh || !ray) {
  59787. return;
  59788. }
  59789. if (this._attachedToMesh._isDisposed) {
  59790. this.detachFromMesh();
  59791. return;
  59792. }
  59793. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  59794. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  59795. };
  59796. RayHelper.prototype.dispose = function () {
  59797. this.hide();
  59798. this.detachFromMesh();
  59799. this.ray = null;
  59800. };
  59801. return RayHelper;
  59802. }());
  59803. BABYLON.RayHelper = RayHelper;
  59804. })(BABYLON || (BABYLON = {}));
  59805. //# sourceMappingURL=babylon.rayHelper.js.map
  59806. var BABYLON;
  59807. (function (BABYLON) {
  59808. // load the inspector using require, if not present in the global namespace.
  59809. var DebugLayer = /** @class */ (function () {
  59810. function DebugLayer(scene) {
  59811. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  59812. this.onPropertyChangedObservable = new BABYLON.Observable();
  59813. this._scene = scene;
  59814. }
  59815. /** Creates the inspector window. */
  59816. DebugLayer.prototype._createInspector = function (config) {
  59817. if (config === void 0) { config = {}; }
  59818. var popup = config.popup || false;
  59819. var initialTab = config.initialTab || 0;
  59820. var parentElement = config.parentElement || null;
  59821. if (!this._inspector) {
  59822. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  59823. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  59824. } // else nothing to do as instance is already created
  59825. };
  59826. DebugLayer.prototype.isVisible = function () {
  59827. if (!this._inspector) {
  59828. return false;
  59829. }
  59830. return true;
  59831. };
  59832. DebugLayer.prototype.hide = function () {
  59833. if (this._inspector) {
  59834. try {
  59835. this._inspector.dispose();
  59836. }
  59837. catch (e) {
  59838. // If the inspector has been removed directly from the inspector tool
  59839. }
  59840. this.onPropertyChangedObservable.clear();
  59841. this._inspector = null;
  59842. }
  59843. };
  59844. /**
  59845. *
  59846. * Launch the debugLayer.
  59847. *
  59848. * initialTab:
  59849. * | Value | Tab Name |
  59850. * | --- | --- |
  59851. * | 0 | Scene |
  59852. * | 1 | Console |
  59853. * | 2 | Stats |
  59854. * | 3 | Textures |
  59855. * | 4 | Mesh |
  59856. * | 5 | Light |
  59857. * | 6 | Material |
  59858. * | 7 | GLTF |
  59859. * | 8 | GUI |
  59860. * | 9 | Physics |
  59861. * | 10 | Camera |
  59862. * | 11 | Audio |
  59863. *
  59864. */
  59865. DebugLayer.prototype.show = function (config) {
  59866. if (config === void 0) { config = {}; }
  59867. if (typeof this.BJSINSPECTOR == 'undefined') {
  59868. // Load inspector and add it to the DOM
  59869. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59870. }
  59871. else {
  59872. // Otherwise creates the inspector
  59873. this._createInspector(config);
  59874. }
  59875. };
  59876. /**
  59877. * Gets the active tab
  59878. * @return the index of the active tab or -1 if the inspector is hidden
  59879. */
  59880. DebugLayer.prototype.getActiveTab = function () {
  59881. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  59882. };
  59883. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  59884. return DebugLayer;
  59885. }());
  59886. BABYLON.DebugLayer = DebugLayer;
  59887. })(BABYLON || (BABYLON = {}));
  59888. //# sourceMappingURL=babylon.debugLayer.js.map
  59889. var BABYLON;
  59890. (function (BABYLON) {
  59891. var Debug;
  59892. (function (Debug) {
  59893. /**
  59894. * Used to show the physics impostor around the specific mesh
  59895. */
  59896. var PhysicsViewer = /** @class */ (function () {
  59897. /**
  59898. * Creates a new PhysicsViewer
  59899. * @param scene defines the hosting scene
  59900. */
  59901. function PhysicsViewer(scene) {
  59902. /** @hidden */
  59903. this._impostors = [];
  59904. /** @hidden */
  59905. this._meshes = [];
  59906. /** @hidden */
  59907. this._numMeshes = 0;
  59908. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59909. var physicEngine = this._scene.getPhysicsEngine();
  59910. if (physicEngine) {
  59911. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  59912. }
  59913. }
  59914. /** @hidden */
  59915. PhysicsViewer.prototype._updateDebugMeshes = function () {
  59916. var plugin = this._physicsEnginePlugin;
  59917. for (var i = 0; i < this._numMeshes; i++) {
  59918. var impostor = this._impostors[i];
  59919. if (!impostor) {
  59920. continue;
  59921. }
  59922. if (impostor.isDisposed) {
  59923. this.hideImpostor(this._impostors[i--]);
  59924. }
  59925. else {
  59926. var mesh = this._meshes[i];
  59927. if (mesh && plugin) {
  59928. plugin.syncMeshWithImpostor(mesh, impostor);
  59929. }
  59930. }
  59931. }
  59932. };
  59933. /**
  59934. * Renders a specified physic impostor
  59935. * @param impostor defines the impostor to render
  59936. */
  59937. PhysicsViewer.prototype.showImpostor = function (impostor) {
  59938. if (!this._scene) {
  59939. return;
  59940. }
  59941. for (var i = 0; i < this._numMeshes; i++) {
  59942. if (this._impostors[i] == impostor) {
  59943. return;
  59944. }
  59945. }
  59946. var debugMesh = this._getDebugMesh(impostor, this._scene);
  59947. if (debugMesh) {
  59948. this._impostors[this._numMeshes] = impostor;
  59949. this._meshes[this._numMeshes] = debugMesh;
  59950. if (this._numMeshes === 0) {
  59951. this._renderFunction = this._updateDebugMeshes.bind(this);
  59952. this._scene.registerBeforeRender(this._renderFunction);
  59953. }
  59954. this._numMeshes++;
  59955. }
  59956. };
  59957. /**
  59958. * Hides a specified physic impostor
  59959. * @param impostor defines the impostor to hide
  59960. */
  59961. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  59962. if (!impostor || !this._scene) {
  59963. return;
  59964. }
  59965. var removed = false;
  59966. for (var i = 0; i < this._numMeshes; i++) {
  59967. if (this._impostors[i] == impostor) {
  59968. var mesh = this._meshes[i];
  59969. if (!mesh) {
  59970. continue;
  59971. }
  59972. this._scene.removeMesh(mesh);
  59973. mesh.dispose();
  59974. this._numMeshes--;
  59975. if (this._numMeshes > 0) {
  59976. this._meshes[i] = this._meshes[this._numMeshes];
  59977. this._impostors[i] = this._impostors[this._numMeshes];
  59978. this._meshes[this._numMeshes] = null;
  59979. this._impostors[this._numMeshes] = null;
  59980. }
  59981. else {
  59982. this._meshes[0] = null;
  59983. this._impostors[0] = null;
  59984. }
  59985. removed = true;
  59986. break;
  59987. }
  59988. }
  59989. if (removed && this._numMeshes === 0) {
  59990. this._scene.unregisterBeforeRender(this._renderFunction);
  59991. }
  59992. };
  59993. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  59994. if (!this._debugMaterial) {
  59995. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59996. this._debugMaterial.wireframe = true;
  59997. }
  59998. return this._debugMaterial;
  59999. };
  60000. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  60001. if (!this._debugBoxMesh) {
  60002. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  60003. this._debugBoxMesh.renderingGroupId = 1;
  60004. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60005. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  60006. scene.removeMesh(this._debugBoxMesh);
  60007. }
  60008. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  60009. };
  60010. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  60011. if (!this._debugSphereMesh) {
  60012. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  60013. this._debugSphereMesh.renderingGroupId = 1;
  60014. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60015. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  60016. scene.removeMesh(this._debugSphereMesh);
  60017. }
  60018. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  60019. };
  60020. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  60021. var mesh = null;
  60022. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  60023. mesh = this._getDebugBoxMesh(scene);
  60024. impostor.getBoxSizeToRef(mesh.scaling);
  60025. }
  60026. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  60027. mesh = this._getDebugSphereMesh(scene);
  60028. var radius = impostor.getRadius();
  60029. mesh.scaling.x = radius * 2;
  60030. mesh.scaling.y = radius * 2;
  60031. mesh.scaling.z = radius * 2;
  60032. }
  60033. return mesh;
  60034. };
  60035. /** Releases all resources */
  60036. PhysicsViewer.prototype.dispose = function () {
  60037. for (var i = 0; i < this._numMeshes; i++) {
  60038. this.hideImpostor(this._impostors[i]);
  60039. }
  60040. if (this._debugBoxMesh) {
  60041. this._debugBoxMesh.dispose();
  60042. }
  60043. if (this._debugSphereMesh) {
  60044. this._debugSphereMesh.dispose();
  60045. }
  60046. if (this._debugMaterial) {
  60047. this._debugMaterial.dispose();
  60048. }
  60049. this._impostors.length = 0;
  60050. this._scene = null;
  60051. this._physicsEnginePlugin = null;
  60052. };
  60053. return PhysicsViewer;
  60054. }());
  60055. Debug.PhysicsViewer = PhysicsViewer;
  60056. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60057. })(BABYLON || (BABYLON = {}));
  60058. //# sourceMappingURL=babylon.physicsViewer.js.map
  60059. var BABYLON;
  60060. (function (BABYLON) {
  60061. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  60062. get: function () {
  60063. return this._forceShowBoundingBoxes || false;
  60064. },
  60065. set: function (value) {
  60066. this._forceShowBoundingBoxes = value;
  60067. // Lazyly creates a BB renderer if needed.
  60068. if (value) {
  60069. this.getBoundingBoxRenderer();
  60070. }
  60071. },
  60072. enumerable: true,
  60073. configurable: true
  60074. });
  60075. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  60076. if (!this._boundingBoxRenderer) {
  60077. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  60078. }
  60079. return this._boundingBoxRenderer;
  60080. };
  60081. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  60082. get: function () {
  60083. return this._showBoundingBox || false;
  60084. },
  60085. set: function (value) {
  60086. this._showBoundingBox = value;
  60087. // Lazyly creates a BB renderer if needed.
  60088. if (value) {
  60089. this.getScene().getBoundingBoxRenderer();
  60090. }
  60091. },
  60092. enumerable: true,
  60093. configurable: true
  60094. });
  60095. var BoundingBoxRenderer = /** @class */ (function () {
  60096. function BoundingBoxRenderer(scene) {
  60097. /**
  60098. * The component name helpfull to identify the component in the list of scene components.
  60099. */
  60100. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  60101. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60102. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60103. this.showBackLines = true;
  60104. this.renderList = new BABYLON.SmartArray(32);
  60105. this._vertexBuffers = {};
  60106. this.scene = scene;
  60107. scene._addComponent(this);
  60108. }
  60109. /**
  60110. * Registers the component in a given scene
  60111. */
  60112. BoundingBoxRenderer.prototype.register = function () {
  60113. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  60114. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  60115. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  60116. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  60117. };
  60118. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  60119. if (mesh.showSubMeshesBoundingBox) {
  60120. var boundingInfo = subMesh.getBoundingInfo();
  60121. if (boundingInfo !== null && boundingInfo !== undefined) {
  60122. this.renderList.push(boundingInfo.boundingBox);
  60123. }
  60124. }
  60125. };
  60126. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  60127. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  60128. var boundingInfo = sourceMesh.getBoundingInfo();
  60129. this.renderList.push(boundingInfo.boundingBox);
  60130. }
  60131. };
  60132. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60133. if (this._colorShader) {
  60134. return;
  60135. }
  60136. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  60137. attributes: [BABYLON.VertexBuffer.PositionKind],
  60138. uniforms: ["world", "viewProjection", "color"]
  60139. });
  60140. var engine = this.scene.getEngine();
  60141. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  60142. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  60143. this._createIndexBuffer();
  60144. };
  60145. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  60146. var engine = this.scene.getEngine();
  60147. 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]);
  60148. };
  60149. /**
  60150. * Rebuilds the elements related to this component in case of
  60151. * context lost for instance.
  60152. */
  60153. BoundingBoxRenderer.prototype.rebuild = function () {
  60154. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60155. if (vb) {
  60156. vb._rebuild();
  60157. }
  60158. this._createIndexBuffer();
  60159. };
  60160. BoundingBoxRenderer.prototype.reset = function () {
  60161. this.renderList.reset();
  60162. };
  60163. BoundingBoxRenderer.prototype.render = function () {
  60164. if (this.renderList.length === 0) {
  60165. return;
  60166. }
  60167. this._prepareRessources();
  60168. if (!this._colorShader.isReady()) {
  60169. return;
  60170. }
  60171. var engine = this.scene.getEngine();
  60172. engine.setDepthWrite(false);
  60173. this._colorShader._preBind();
  60174. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  60175. var boundingBox = this.renderList.data[boundingBoxIndex];
  60176. var min = boundingBox.minimum;
  60177. var max = boundingBox.maximum;
  60178. var diff = max.subtract(min);
  60179. var median = min.add(diff.scale(0.5));
  60180. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60181. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60182. .multiply(boundingBox.getWorldMatrix());
  60183. // VBOs
  60184. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60185. if (this.showBackLines) {
  60186. // Back
  60187. engine.setDepthFunctionToGreaterOrEqual();
  60188. this.scene.resetCachedMaterial();
  60189. this._colorShader.setColor4("color", this.backColor.toColor4());
  60190. this._colorShader.bind(worldMatrix);
  60191. // Draw order
  60192. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60193. }
  60194. // Front
  60195. engine.setDepthFunctionToLess();
  60196. this.scene.resetCachedMaterial();
  60197. this._colorShader.setColor4("color", this.frontColor.toColor4());
  60198. this._colorShader.bind(worldMatrix);
  60199. // Draw order
  60200. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60201. }
  60202. this._colorShader.unbind();
  60203. engine.setDepthFunctionToLessOrEqual();
  60204. engine.setDepthWrite(true);
  60205. };
  60206. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  60207. this._prepareRessources();
  60208. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  60209. return;
  60210. }
  60211. var engine = this.scene.getEngine();
  60212. engine.setDepthWrite(false);
  60213. engine.setColorWrite(false);
  60214. this._colorShader._preBind();
  60215. var boundingBox = mesh._boundingInfo.boundingBox;
  60216. var min = boundingBox.minimum;
  60217. var max = boundingBox.maximum;
  60218. var diff = max.subtract(min);
  60219. var median = min.add(diff.scale(0.5));
  60220. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60221. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60222. .multiply(boundingBox.getWorldMatrix());
  60223. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60224. engine.setDepthFunctionToLess();
  60225. this.scene.resetCachedMaterial();
  60226. this._colorShader.bind(worldMatrix);
  60227. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60228. this._colorShader.unbind();
  60229. engine.setDepthFunctionToLessOrEqual();
  60230. engine.setDepthWrite(true);
  60231. engine.setColorWrite(true);
  60232. };
  60233. BoundingBoxRenderer.prototype.dispose = function () {
  60234. if (!this._colorShader) {
  60235. return;
  60236. }
  60237. this.renderList.dispose();
  60238. this._colorShader.dispose();
  60239. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60240. if (buffer) {
  60241. buffer.dispose();
  60242. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60243. }
  60244. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  60245. };
  60246. return BoundingBoxRenderer;
  60247. }());
  60248. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60249. })(BABYLON || (BABYLON = {}));
  60250. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60251. var BABYLON;
  60252. (function (BABYLON) {
  60253. BABYLON.Engine.prototype.createTransformFeedback = function () {
  60254. return this._gl.createTransformFeedback();
  60255. };
  60256. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  60257. this._gl.deleteTransformFeedback(value);
  60258. };
  60259. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  60260. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  60261. };
  60262. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  60263. if (usePoints === void 0) { usePoints = true; }
  60264. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  60265. };
  60266. BABYLON.Engine.prototype.endTransformFeedback = function () {
  60267. this._gl.endTransformFeedback();
  60268. };
  60269. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  60270. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  60271. };
  60272. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  60273. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  60274. };
  60275. })(BABYLON || (BABYLON = {}));
  60276. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  60277. var BABYLON;
  60278. (function (BABYLON) {
  60279. /**
  60280. * This represents a GPU particle system in Babylon
  60281. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  60282. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  60283. */
  60284. var GPUParticleSystem = /** @class */ (function (_super) {
  60285. __extends(GPUParticleSystem, _super);
  60286. /**
  60287. * Instantiates a GPU particle system.
  60288. * 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.
  60289. * @param name The name of the particle system
  60290. * @param options The options used to create the system
  60291. * @param scene The scene the particle system belongs to
  60292. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60293. */
  60294. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  60295. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60296. var _this = _super.call(this, name) || this;
  60297. /**
  60298. * The layer mask we are rendering the particles through.
  60299. */
  60300. _this.layerMask = 0x0FFFFFFF;
  60301. _this._accumulatedCount = 0;
  60302. _this._targetIndex = 0;
  60303. _this._currentRenderId = -1;
  60304. _this._started = false;
  60305. _this._stopped = false;
  60306. _this._timeDelta = 0;
  60307. _this._attributesStrideSize = 21;
  60308. _this._actualFrame = 0;
  60309. _this._rawTextureWidth = 256;
  60310. /**
  60311. * An event triggered when the system is disposed.
  60312. */
  60313. _this.onDisposeObservable = new BABYLON.Observable();
  60314. /**
  60315. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60316. * to override the particles.
  60317. */
  60318. _this.forceDepthWrite = false;
  60319. _this._preWarmDone = false;
  60320. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60321. // Setup the default processing configuration to the scene.
  60322. _this._attachImageProcessingConfiguration(null);
  60323. _this._engine = _this._scene.getEngine();
  60324. if (!options.randomTextureSize) {
  60325. delete options.randomTextureSize;
  60326. }
  60327. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  60328. var optionsAsNumber = options;
  60329. if (isFinite(optionsAsNumber)) {
  60330. fullOptions.capacity = optionsAsNumber;
  60331. }
  60332. _this._capacity = fullOptions.capacity;
  60333. _this._activeCount = fullOptions.capacity;
  60334. _this._currentActiveCount = 0;
  60335. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60336. _this._scene.particleSystems.push(_this);
  60337. _this._updateEffectOptions = {
  60338. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60339. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  60340. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  60341. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  60342. uniformBuffersNames: [],
  60343. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  60344. defines: "",
  60345. fallbacks: null,
  60346. onCompiled: null,
  60347. onError: null,
  60348. indexParameters: null,
  60349. maxSimultaneousLights: 0,
  60350. transformFeedbackVaryings: []
  60351. };
  60352. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60353. // Random data
  60354. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  60355. var d = [];
  60356. for (var i = 0; i < maxTextureSize; ++i) {
  60357. d.push(Math.random());
  60358. d.push(Math.random());
  60359. d.push(Math.random());
  60360. d.push(Math.random());
  60361. }
  60362. _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);
  60363. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60364. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60365. d = [];
  60366. for (var i = 0; i < maxTextureSize; ++i) {
  60367. d.push(Math.random());
  60368. d.push(Math.random());
  60369. d.push(Math.random());
  60370. d.push(Math.random());
  60371. }
  60372. _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);
  60373. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60374. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60375. _this._randomTextureSize = maxTextureSize;
  60376. return _this;
  60377. }
  60378. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  60379. /**
  60380. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  60381. */
  60382. get: function () {
  60383. if (!BABYLON.Engine.LastCreatedEngine) {
  60384. return false;
  60385. }
  60386. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  60387. },
  60388. enumerable: true,
  60389. configurable: true
  60390. });
  60391. /**
  60392. * Gets the maximum number of particles active at the same time.
  60393. * @returns The max number of active particles.
  60394. */
  60395. GPUParticleSystem.prototype.getCapacity = function () {
  60396. return this._capacity;
  60397. };
  60398. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  60399. /**
  60400. * Gets or set the number of active particles
  60401. */
  60402. get: function () {
  60403. return this._activeCount;
  60404. },
  60405. set: function (value) {
  60406. this._activeCount = Math.min(value, this._capacity);
  60407. },
  60408. enumerable: true,
  60409. configurable: true
  60410. });
  60411. /**
  60412. * Is this system ready to be used/rendered
  60413. * @return true if the system is ready
  60414. */
  60415. GPUParticleSystem.prototype.isReady = function () {
  60416. if (!this._updateEffect) {
  60417. this._recreateUpdateEffect();
  60418. this._recreateRenderEffect();
  60419. return false;
  60420. }
  60421. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60422. return false;
  60423. }
  60424. return true;
  60425. };
  60426. /**
  60427. * Gets Wether the system has been started.
  60428. * @returns True if it has been started, otherwise false.
  60429. */
  60430. GPUParticleSystem.prototype.isStarted = function () {
  60431. return this._started;
  60432. };
  60433. /**
  60434. * Starts the particle system and begins to emit
  60435. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  60436. */
  60437. GPUParticleSystem.prototype.start = function (delay) {
  60438. var _this = this;
  60439. if (delay === void 0) { delay = 0; }
  60440. if (delay) {
  60441. setTimeout(function () {
  60442. _this.start(0);
  60443. }, delay);
  60444. return;
  60445. }
  60446. this._started = true;
  60447. this._stopped = false;
  60448. this._preWarmDone = false;
  60449. };
  60450. /**
  60451. * Stops the particle system.
  60452. */
  60453. GPUParticleSystem.prototype.stop = function () {
  60454. this._stopped = true;
  60455. };
  60456. /**
  60457. * Remove all active particles
  60458. */
  60459. GPUParticleSystem.prototype.reset = function () {
  60460. this._releaseBuffers();
  60461. this._releaseVAOs();
  60462. this._currentActiveCount = 0;
  60463. this._targetIndex = 0;
  60464. };
  60465. /**
  60466. * Returns the string "GPUParticleSystem"
  60467. * @returns a string containing the class name
  60468. */
  60469. GPUParticleSystem.prototype.getClassName = function () {
  60470. return "GPUParticleSystem";
  60471. };
  60472. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  60473. if (!gradients) {
  60474. return this;
  60475. }
  60476. var index = 0;
  60477. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60478. var valueGradient = gradients_1[_i];
  60479. if (valueGradient.gradient === gradient) {
  60480. gradients.splice(index, 1);
  60481. break;
  60482. }
  60483. index++;
  60484. }
  60485. if (texture) {
  60486. texture.dispose();
  60487. }
  60488. this._releaseBuffers();
  60489. return this;
  60490. };
  60491. /**
  60492. * Adds a new color gradient
  60493. * @param gradient defines the gradient to use (between 0 and 1)
  60494. * @param color defines the color to affect to the specified gradient
  60495. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  60496. * @returns the current particle system
  60497. */
  60498. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  60499. if (!this._colorGradients) {
  60500. this._colorGradients = [];
  60501. }
  60502. var colorGradient = new BABYLON.ColorGradient();
  60503. colorGradient.gradient = gradient;
  60504. colorGradient.color1 = color1;
  60505. this._colorGradients.push(colorGradient);
  60506. this._colorGradients.sort(function (a, b) {
  60507. if (a.gradient < b.gradient) {
  60508. return -1;
  60509. }
  60510. else if (a.gradient > b.gradient) {
  60511. return 1;
  60512. }
  60513. return 0;
  60514. });
  60515. if (this._colorGradientsTexture) {
  60516. this._colorGradientsTexture.dispose();
  60517. this._colorGradientsTexture = null;
  60518. }
  60519. this._releaseBuffers();
  60520. return this;
  60521. };
  60522. /**
  60523. * Remove a specific color gradient
  60524. * @param gradient defines the gradient to remove
  60525. * @returns the current particle system
  60526. */
  60527. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  60528. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  60529. this._colorGradientsTexture = null;
  60530. return this;
  60531. };
  60532. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  60533. var valueGradient = new BABYLON.FactorGradient();
  60534. valueGradient.gradient = gradient;
  60535. valueGradient.factor1 = factor;
  60536. factorGradients.push(valueGradient);
  60537. factorGradients.sort(function (a, b) {
  60538. if (a.gradient < b.gradient) {
  60539. return -1;
  60540. }
  60541. else if (a.gradient > b.gradient) {
  60542. return 1;
  60543. }
  60544. return 0;
  60545. });
  60546. this._releaseBuffers();
  60547. };
  60548. /**
  60549. * Adds a new size gradient
  60550. * @param gradient defines the gradient to use (between 0 and 1)
  60551. * @param factor defines the size factor to affect to the specified gradient
  60552. * @returns the current particle system
  60553. */
  60554. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  60555. if (!this._sizeGradients) {
  60556. this._sizeGradients = [];
  60557. }
  60558. this._addFactorGradient(this._sizeGradients, gradient, factor);
  60559. if (this._sizeGradientsTexture) {
  60560. this._sizeGradientsTexture.dispose();
  60561. this._sizeGradientsTexture = null;
  60562. }
  60563. this._releaseBuffers();
  60564. return this;
  60565. };
  60566. /**
  60567. * Remove a specific size gradient
  60568. * @param gradient defines the gradient to remove
  60569. * @returns the current particle system
  60570. */
  60571. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60572. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  60573. this._sizeGradientsTexture = null;
  60574. return this;
  60575. };
  60576. /**
  60577. * Adds a new angular speed gradient
  60578. * @param gradient defines the gradient to use (between 0 and 1)
  60579. * @param factor defines the angular speed to affect to the specified gradient
  60580. * @returns the current particle system
  60581. */
  60582. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  60583. if (!this._angularSpeedGradients) {
  60584. this._angularSpeedGradients = [];
  60585. }
  60586. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  60587. if (this._angularSpeedGradientsTexture) {
  60588. this._angularSpeedGradientsTexture.dispose();
  60589. this._angularSpeedGradientsTexture = null;
  60590. }
  60591. this._releaseBuffers();
  60592. return this;
  60593. };
  60594. /**
  60595. * Remove a specific angular speed gradient
  60596. * @param gradient defines the gradient to remove
  60597. * @returns the current particle system
  60598. */
  60599. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60600. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  60601. this._angularSpeedGradientsTexture = null;
  60602. return this;
  60603. };
  60604. /**
  60605. * Adds a new velocity gradient
  60606. * @param gradient defines the gradient to use (between 0 and 1)
  60607. * @param factor defines the velocity to affect to the specified gradient
  60608. * @returns the current particle system
  60609. */
  60610. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  60611. if (!this._velocityGradients) {
  60612. this._velocityGradients = [];
  60613. }
  60614. this._addFactorGradient(this._velocityGradients, gradient, factor);
  60615. if (this._velocityGradientsTexture) {
  60616. this._velocityGradientsTexture.dispose();
  60617. this._velocityGradientsTexture = null;
  60618. }
  60619. this._releaseBuffers();
  60620. return this;
  60621. };
  60622. /**
  60623. * Remove a specific velocity gradient
  60624. * @param gradient defines the gradient to remove
  60625. * @returns the current particle system
  60626. */
  60627. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60628. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  60629. this._velocityGradientsTexture = null;
  60630. return this;
  60631. };
  60632. /**
  60633. * Adds a new limit velocity gradient
  60634. * @param gradient defines the gradient to use (between 0 and 1)
  60635. * @param factor defines the limit velocity value to affect to the specified gradient
  60636. * @returns the current particle system
  60637. */
  60638. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  60639. if (!this._limitVelocityGradients) {
  60640. this._limitVelocityGradients = [];
  60641. }
  60642. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  60643. if (this._limitVelocityGradientsTexture) {
  60644. this._limitVelocityGradientsTexture.dispose();
  60645. this._limitVelocityGradientsTexture = null;
  60646. }
  60647. this._releaseBuffers();
  60648. return this;
  60649. };
  60650. /**
  60651. * Remove a specific limit velocity gradient
  60652. * @param gradient defines the gradient to remove
  60653. * @returns the current particle system
  60654. */
  60655. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  60656. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  60657. this._limitVelocityGradientsTexture = null;
  60658. return this;
  60659. };
  60660. GPUParticleSystem.prototype._reset = function () {
  60661. this._releaseBuffers();
  60662. };
  60663. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60664. var updateVertexBuffers = {};
  60665. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60666. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60667. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60668. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60669. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60670. var offset = 12;
  60671. if (!this._colorGradientsTexture) {
  60672. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60673. offset += 4;
  60674. }
  60675. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60676. offset += 3;
  60677. if (!this._isBillboardBased) {
  60678. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60679. offset += 3;
  60680. }
  60681. if (this._angularSpeedGradientsTexture) {
  60682. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60683. offset += 1;
  60684. }
  60685. else {
  60686. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60687. offset += 2;
  60688. }
  60689. if (this._isAnimationSheetEnabled) {
  60690. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60691. offset += 1;
  60692. }
  60693. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60694. this._engine.bindArrayBuffer(null);
  60695. return vao;
  60696. };
  60697. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60698. var renderVertexBuffers = {};
  60699. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  60700. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  60701. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  60702. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  60703. var offset = 12;
  60704. if (!this._colorGradientsTexture) {
  60705. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  60706. offset += 4;
  60707. }
  60708. offset += 3; // Direction
  60709. if (!this._isBillboardBased) {
  60710. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  60711. offset += 3;
  60712. }
  60713. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  60714. if (this._angularSpeedGradientsTexture) {
  60715. offset++;
  60716. }
  60717. else {
  60718. offset += 2;
  60719. }
  60720. if (this._isAnimationSheetEnabled) {
  60721. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  60722. offset += 1;
  60723. }
  60724. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  60725. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  60726. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  60727. this._engine.bindArrayBuffer(null);
  60728. return vao;
  60729. };
  60730. GPUParticleSystem.prototype._initialize = function (force) {
  60731. if (force === void 0) { force = false; }
  60732. if (this._buffer0 && !force) {
  60733. return;
  60734. }
  60735. var engine = this._scene.getEngine();
  60736. var data = new Array();
  60737. if (!this.isBillboardBased) {
  60738. this._attributesStrideSize += 3;
  60739. }
  60740. if (this._colorGradientsTexture) {
  60741. this._attributesStrideSize -= 4;
  60742. }
  60743. if (this._angularSpeedGradientsTexture) {
  60744. this._attributesStrideSize -= 1;
  60745. }
  60746. if (this._isAnimationSheetEnabled) {
  60747. this._attributesStrideSize += 1;
  60748. }
  60749. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  60750. // position
  60751. data.push(0.0);
  60752. data.push(0.0);
  60753. data.push(0.0);
  60754. // Age and life
  60755. data.push(0.0); // create the particle as a dead one to create a new one at start
  60756. data.push(0.0);
  60757. // Seed
  60758. data.push(Math.random());
  60759. data.push(Math.random());
  60760. data.push(Math.random());
  60761. data.push(Math.random());
  60762. // Size
  60763. data.push(0.0);
  60764. data.push(0.0);
  60765. data.push(0.0);
  60766. if (!this._colorGradientsTexture) {
  60767. // color
  60768. data.push(0.0);
  60769. data.push(0.0);
  60770. data.push(0.0);
  60771. data.push(0.0);
  60772. }
  60773. // direction
  60774. data.push(0.0);
  60775. data.push(0.0);
  60776. data.push(0.0);
  60777. if (!this.isBillboardBased) {
  60778. // initialDirection
  60779. data.push(0.0);
  60780. data.push(0.0);
  60781. data.push(0.0);
  60782. }
  60783. // angle
  60784. data.push(0.0);
  60785. if (!this._angularSpeedGradientsTexture) {
  60786. data.push(0.0);
  60787. }
  60788. if (this._isAnimationSheetEnabled) {
  60789. data.push(0.0);
  60790. }
  60791. }
  60792. // Sprite data
  60793. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  60794. -0.5, 0.5, 0, 1,
  60795. -0.5, -0.5, 0, 0,
  60796. 0.5, -0.5, 1, 0]);
  60797. // Buffers
  60798. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60799. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60800. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  60801. // Update VAO
  60802. this._updateVAO = [];
  60803. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  60804. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  60805. // Render VAO
  60806. this._renderVAO = [];
  60807. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  60808. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  60809. // Links
  60810. this._sourceBuffer = this._buffer0;
  60811. this._targetBuffer = this._buffer1;
  60812. };
  60813. /** @hidden */
  60814. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  60815. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  60816. if (this._isBillboardBased) {
  60817. defines += "\n#define BILLBOARD";
  60818. }
  60819. if (this._colorGradientsTexture) {
  60820. defines += "\n#define COLORGRADIENTS";
  60821. }
  60822. if (this._sizeGradientsTexture) {
  60823. defines += "\n#define SIZEGRADIENTS";
  60824. }
  60825. if (this._angularSpeedGradientsTexture) {
  60826. defines += "\n#define ANGULARSPEEDGRADIENTS";
  60827. }
  60828. if (this._velocityGradientsTexture) {
  60829. defines += "\n#define VELOCITYGRADIENTS";
  60830. }
  60831. if (this.isAnimationSheetEnabled) {
  60832. defines += "\n#define ANIMATESHEET";
  60833. }
  60834. if (this.noiseTexture) {
  60835. defines += "\n#define NOISE";
  60836. }
  60837. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  60838. return;
  60839. }
  60840. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  60841. if (!this._colorGradientsTexture) {
  60842. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  60843. }
  60844. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  60845. if (!this._isBillboardBased) {
  60846. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  60847. }
  60848. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  60849. if (this.isAnimationSheetEnabled) {
  60850. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  60851. }
  60852. this._updateEffectOptions.defines = defines;
  60853. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  60854. };
  60855. /** @hidden */
  60856. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  60857. var defines = "";
  60858. if (this._scene.clipPlane) {
  60859. defines = "\n#define CLIPPLANE";
  60860. }
  60861. if (this._isBillboardBased) {
  60862. defines += "\n#define BILLBOARD";
  60863. switch (this.billboardMode) {
  60864. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  60865. defines += "\n#define BILLBOARDY";
  60866. break;
  60867. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  60868. default:
  60869. break;
  60870. }
  60871. }
  60872. if (this._colorGradientsTexture) {
  60873. defines += "\n#define COLORGRADIENTS";
  60874. }
  60875. if (this.isAnimationSheetEnabled) {
  60876. defines += "\n#define ANIMATESHEET";
  60877. }
  60878. if (this._imageProcessingConfiguration) {
  60879. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  60880. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  60881. }
  60882. if (this._renderEffect && this._renderEffect.defines === defines) {
  60883. return;
  60884. }
  60885. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"];
  60886. var samplers = ["textureSampler", "colorGradientSampler"];
  60887. if (BABYLON.ImageProcessingConfiguration) {
  60888. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  60889. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  60890. }
  60891. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  60892. };
  60893. /**
  60894. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60895. * @param preWarm defines if we are in the pre-warmimg phase
  60896. */
  60897. GPUParticleSystem.prototype.animate = function (preWarm) {
  60898. if (preWarm === void 0) { preWarm = false; }
  60899. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60900. this._actualFrame += this._timeDelta;
  60901. if (!this._stopped) {
  60902. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60903. this.stop();
  60904. }
  60905. }
  60906. };
  60907. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  60908. var texture = this[textureName];
  60909. if (!factorGradients || !factorGradients.length || texture) {
  60910. return;
  60911. }
  60912. var data = new Float32Array(this._rawTextureWidth);
  60913. for (var x = 0; x < this._rawTextureWidth; x++) {
  60914. var ratio = x / this._rawTextureWidth;
  60915. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  60916. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60917. });
  60918. }
  60919. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60920. };
  60921. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  60922. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  60923. };
  60924. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  60925. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  60926. };
  60927. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  60928. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  60929. };
  60930. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  60931. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  60932. return;
  60933. }
  60934. var data = new Uint8Array(this._rawTextureWidth * 4);
  60935. var tmpColor = BABYLON.Tmp.Color4[0];
  60936. for (var x = 0; x < this._rawTextureWidth; x++) {
  60937. var ratio = x / this._rawTextureWidth;
  60938. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  60939. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  60940. data[x * 4] = tmpColor.r * 255;
  60941. data[x * 4 + 1] = tmpColor.g * 255;
  60942. data[x * 4 + 2] = tmpColor.b * 255;
  60943. data[x * 4 + 3] = tmpColor.a * 255;
  60944. });
  60945. }
  60946. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60947. };
  60948. /**
  60949. * Renders the particle system in its current state
  60950. * @param preWarm defines if the system should only update the particles but not render them
  60951. * @returns the current number of particles
  60952. */
  60953. GPUParticleSystem.prototype.render = function (preWarm) {
  60954. if (preWarm === void 0) { preWarm = false; }
  60955. if (!this._started) {
  60956. return 0;
  60957. }
  60958. this._createColorGradientTexture();
  60959. this._createSizeGradientTexture();
  60960. this._createAngularSpeedGradientTexture();
  60961. this._createVelocityGradientTexture();
  60962. this._recreateUpdateEffect();
  60963. this._recreateRenderEffect();
  60964. if (!this.isReady()) {
  60965. return 0;
  60966. }
  60967. if (!preWarm) {
  60968. if (!this._preWarmDone && this.preWarmCycles) {
  60969. for (var index = 0; index < this.preWarmCycles; index++) {
  60970. this.animate(true);
  60971. this.render(true);
  60972. }
  60973. this._preWarmDone = true;
  60974. }
  60975. if (this._currentRenderId === this._scene.getRenderId()) {
  60976. return 0;
  60977. }
  60978. this._currentRenderId = this._scene.getRenderId();
  60979. }
  60980. // Get everything ready to render
  60981. this._initialize();
  60982. this._accumulatedCount += this.emitRate * this._timeDelta;
  60983. if (this._accumulatedCount > 1) {
  60984. var intPart = this._accumulatedCount | 0;
  60985. this._accumulatedCount -= intPart;
  60986. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  60987. }
  60988. if (!this._currentActiveCount) {
  60989. return 0;
  60990. }
  60991. // Enable update effect
  60992. this._engine.enableEffect(this._updateEffect);
  60993. this._engine.setState(false);
  60994. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  60995. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  60996. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  60997. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  60998. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  60999. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  61000. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  61001. if (!this._colorGradientsTexture) {
  61002. this._updateEffect.setDirectColor4("color1", this.color1);
  61003. this._updateEffect.setDirectColor4("color2", this.color2);
  61004. }
  61005. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  61006. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  61007. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  61008. this._updateEffect.setVector3("gravity", this.gravity);
  61009. if (this._sizeGradientsTexture) {
  61010. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  61011. }
  61012. if (this._angularSpeedGradientsTexture) {
  61013. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  61014. }
  61015. if (this._velocityGradientsTexture) {
  61016. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  61017. }
  61018. if (this.particleEmitterType) {
  61019. this.particleEmitterType.applyToShader(this._updateEffect);
  61020. }
  61021. if (this._isAnimationSheetEnabled) {
  61022. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  61023. }
  61024. if (this.noiseTexture) {
  61025. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  61026. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  61027. }
  61028. var emitterWM;
  61029. if (this.emitter.position) {
  61030. var emitterMesh = this.emitter;
  61031. emitterWM = emitterMesh.getWorldMatrix();
  61032. }
  61033. else {
  61034. var emitterPosition = this.emitter;
  61035. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61036. }
  61037. this._updateEffect.setMatrix("emitterWM", emitterWM);
  61038. // Bind source VAO
  61039. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  61040. // Update
  61041. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  61042. this._engine.setRasterizerState(false);
  61043. this._engine.beginTransformFeedback(true);
  61044. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  61045. this._engine.endTransformFeedback();
  61046. this._engine.setRasterizerState(true);
  61047. this._engine.bindTransformFeedbackBuffer(null);
  61048. if (!preWarm) {
  61049. // Enable render effect
  61050. this._engine.enableEffect(this._renderEffect);
  61051. var viewMatrix = this._scene.getViewMatrix();
  61052. this._renderEffect.setMatrix("view", viewMatrix);
  61053. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  61054. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  61055. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  61056. if (this._colorGradientsTexture) {
  61057. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  61058. }
  61059. else {
  61060. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  61061. }
  61062. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61063. var baseSize = this.particleTexture.getBaseSize();
  61064. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61065. }
  61066. if (this._isBillboardBased) {
  61067. var camera = this._scene.activeCamera;
  61068. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  61069. }
  61070. if (this._scene.clipPlane) {
  61071. var clipPlane = this._scene.clipPlane;
  61072. var invView = viewMatrix.clone();
  61073. invView.invert();
  61074. this._renderEffect.setMatrix("invView", invView);
  61075. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  61076. }
  61077. // image processing
  61078. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61079. this._imageProcessingConfiguration.bind(this._renderEffect);
  61080. }
  61081. // Draw order
  61082. switch (this.blendMode) {
  61083. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  61084. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61085. break;
  61086. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  61087. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61088. break;
  61089. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  61090. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61091. break;
  61092. }
  61093. if (this.forceDepthWrite) {
  61094. this._engine.setDepthWrite(true);
  61095. }
  61096. // Bind source VAO
  61097. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  61098. // Render
  61099. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  61100. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61101. }
  61102. // Switch VAOs
  61103. this._targetIndex++;
  61104. if (this._targetIndex === 2) {
  61105. this._targetIndex = 0;
  61106. }
  61107. // Switch buffers
  61108. var tmpBuffer = this._sourceBuffer;
  61109. this._sourceBuffer = this._targetBuffer;
  61110. this._targetBuffer = tmpBuffer;
  61111. return this._currentActiveCount;
  61112. };
  61113. /**
  61114. * Rebuilds the particle system
  61115. */
  61116. GPUParticleSystem.prototype.rebuild = function () {
  61117. this._initialize(true);
  61118. };
  61119. GPUParticleSystem.prototype._releaseBuffers = function () {
  61120. if (this._buffer0) {
  61121. this._buffer0.dispose();
  61122. this._buffer0 = null;
  61123. }
  61124. if (this._buffer1) {
  61125. this._buffer1.dispose();
  61126. this._buffer1 = null;
  61127. }
  61128. if (this._spriteBuffer) {
  61129. this._spriteBuffer.dispose();
  61130. this._spriteBuffer = null;
  61131. }
  61132. };
  61133. GPUParticleSystem.prototype._releaseVAOs = function () {
  61134. if (!this._updateVAO) {
  61135. return;
  61136. }
  61137. for (var index = 0; index < this._updateVAO.length; index++) {
  61138. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  61139. }
  61140. this._updateVAO = [];
  61141. for (var index = 0; index < this._renderVAO.length; index++) {
  61142. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  61143. }
  61144. this._renderVAO = [];
  61145. };
  61146. /**
  61147. * Disposes the particle system and free the associated resources
  61148. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61149. */
  61150. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  61151. if (disposeTexture === void 0) { disposeTexture = true; }
  61152. var index = this._scene.particleSystems.indexOf(this);
  61153. if (index > -1) {
  61154. this._scene.particleSystems.splice(index, 1);
  61155. }
  61156. this._releaseBuffers();
  61157. this._releaseVAOs();
  61158. if (this._colorGradientsTexture) {
  61159. this._colorGradientsTexture.dispose();
  61160. this._colorGradientsTexture = null;
  61161. }
  61162. if (this._sizeGradientsTexture) {
  61163. this._sizeGradientsTexture.dispose();
  61164. this._sizeGradientsTexture = null;
  61165. }
  61166. if (this._angularSpeedGradientsTexture) {
  61167. this._angularSpeedGradientsTexture.dispose();
  61168. this._angularSpeedGradientsTexture = null;
  61169. }
  61170. if (this._velocityGradientsTexture) {
  61171. this._velocityGradientsTexture.dispose();
  61172. this._velocityGradientsTexture = null;
  61173. }
  61174. if (this._limitVelocityGradientsTexture) {
  61175. this._limitVelocityGradientsTexture.dispose();
  61176. this._limitVelocityGradientsTexture = null;
  61177. }
  61178. if (this._randomTexture) {
  61179. this._randomTexture.dispose();
  61180. this._randomTexture = null;
  61181. }
  61182. if (this._randomTexture2) {
  61183. this._randomTexture2.dispose();
  61184. this._randomTexture2 = null;
  61185. }
  61186. if (disposeTexture && this.particleTexture) {
  61187. this.particleTexture.dispose();
  61188. this.particleTexture = null;
  61189. }
  61190. if (disposeTexture && this.noiseTexture) {
  61191. this.noiseTexture.dispose();
  61192. this.noiseTexture = null;
  61193. }
  61194. // Callback
  61195. this.onDisposeObservable.notifyObservers(this);
  61196. this.onDisposeObservable.clear();
  61197. };
  61198. /**
  61199. * Clones the particle system.
  61200. * @param name The name of the cloned object
  61201. * @param newEmitter The new emitter to use
  61202. * @returns the cloned particle system
  61203. */
  61204. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  61205. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  61206. BABYLON.Tools.DeepCopy(this, result);
  61207. if (newEmitter === undefined) {
  61208. newEmitter = this.emitter;
  61209. }
  61210. result.emitter = newEmitter;
  61211. if (this.particleTexture) {
  61212. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61213. }
  61214. return result;
  61215. };
  61216. /**
  61217. * Serializes the particle system to a JSON object.
  61218. * @returns the JSON object
  61219. */
  61220. GPUParticleSystem.prototype.serialize = function () {
  61221. var serializationObject = {};
  61222. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  61223. serializationObject.activeParticleCount = this.activeParticleCount;
  61224. return serializationObject;
  61225. };
  61226. /**
  61227. * Parses a JSON object to create a GPU particle system.
  61228. * @param parsedParticleSystem The JSON object to parse
  61229. * @param scene The scene to create the particle system in
  61230. * @param rootUrl The root url to use to load external dependencies like texture
  61231. * @returns the parsed GPU particle system
  61232. */
  61233. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  61234. var name = parsedParticleSystem.name;
  61235. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  61236. if (parsedParticleSystem.activeParticleCount) {
  61237. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  61238. }
  61239. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61240. return particleSystem;
  61241. };
  61242. return GPUParticleSystem;
  61243. }(BABYLON.BaseParticleSystem));
  61244. BABYLON.GPUParticleSystem = GPUParticleSystem;
  61245. })(BABYLON || (BABYLON = {}));
  61246. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  61247. var BABYLON;
  61248. (function (BABYLON) {
  61249. /**
  61250. * Represents one particle of a solid particle system.
  61251. */
  61252. var SolidParticle = /** @class */ (function () {
  61253. /**
  61254. * Creates a Solid Particle object.
  61255. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  61256. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  61257. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  61258. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  61259. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  61260. * @param shapeId (integer) is the model shape identifier in the SPS.
  61261. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  61262. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  61263. */
  61264. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  61265. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  61266. /**
  61267. * particle global index
  61268. */
  61269. this.idx = 0;
  61270. /**
  61271. * The color of the particle
  61272. */
  61273. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61274. /**
  61275. * The world space position of the particle.
  61276. */
  61277. this.position = BABYLON.Vector3.Zero();
  61278. /**
  61279. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  61280. */
  61281. this.rotation = BABYLON.Vector3.Zero();
  61282. /**
  61283. * The scaling of the particle.
  61284. */
  61285. this.scaling = BABYLON.Vector3.One();
  61286. /**
  61287. * The uvs of the particle.
  61288. */
  61289. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  61290. /**
  61291. * The current speed of the particle.
  61292. */
  61293. this.velocity = BABYLON.Vector3.Zero();
  61294. /**
  61295. * The pivot point in the particle local space.
  61296. */
  61297. this.pivot = BABYLON.Vector3.Zero();
  61298. /**
  61299. * Must the particle be translated from its pivot point in its local space ?
  61300. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  61301. * Default : false
  61302. */
  61303. this.translateFromPivot = false;
  61304. /**
  61305. * Is the particle active or not ?
  61306. */
  61307. this.alive = true;
  61308. /**
  61309. * Is the particle visible or not ?
  61310. */
  61311. this.isVisible = true;
  61312. /**
  61313. * Index of this particle in the global "positions" array (Internal use)
  61314. * @hidden
  61315. */
  61316. this._pos = 0;
  61317. /**
  61318. * @hidden Index of this particle in the global "indices" array (Internal use)
  61319. */
  61320. this._ind = 0;
  61321. /**
  61322. * ModelShape id of this particle
  61323. */
  61324. this.shapeId = 0;
  61325. /**
  61326. * Index of the particle in its shape id (Internal use)
  61327. */
  61328. this.idxInShape = 0;
  61329. /**
  61330. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  61331. */
  61332. this._stillInvisible = false;
  61333. /**
  61334. * @hidden Last computed particle rotation matrix
  61335. */
  61336. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  61337. /**
  61338. * Parent particle Id, if any.
  61339. * Default null.
  61340. */
  61341. this.parentId = null;
  61342. /**
  61343. * @hidden Internal global position in the SPS.
  61344. */
  61345. this._globalPosition = BABYLON.Vector3.Zero();
  61346. this.idx = particleIndex;
  61347. this._pos = positionIndex;
  61348. this._ind = indiceIndex;
  61349. this._model = model;
  61350. this.shapeId = shapeId;
  61351. this.idxInShape = idxInShape;
  61352. this._sps = sps;
  61353. if (modelBoundingInfo) {
  61354. this._modelBoundingInfo = modelBoundingInfo;
  61355. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  61356. }
  61357. }
  61358. Object.defineProperty(SolidParticle.prototype, "scale", {
  61359. /**
  61360. * Legacy support, changed scale to scaling
  61361. */
  61362. get: function () {
  61363. return this.scaling;
  61364. },
  61365. /**
  61366. * Legacy support, changed scale to scaling
  61367. */
  61368. set: function (scale) {
  61369. this.scaling = scale;
  61370. },
  61371. enumerable: true,
  61372. configurable: true
  61373. });
  61374. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  61375. /**
  61376. * Legacy support, changed quaternion to rotationQuaternion
  61377. */
  61378. get: function () {
  61379. return this.rotationQuaternion;
  61380. },
  61381. /**
  61382. * Legacy support, changed quaternion to rotationQuaternion
  61383. */
  61384. set: function (q) {
  61385. this.rotationQuaternion = q;
  61386. },
  61387. enumerable: true,
  61388. configurable: true
  61389. });
  61390. /**
  61391. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  61392. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  61393. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  61394. * @returns true if it intersects
  61395. */
  61396. SolidParticle.prototype.intersectsMesh = function (target) {
  61397. if (!this._boundingInfo || !target._boundingInfo) {
  61398. return false;
  61399. }
  61400. if (this._sps._bSphereOnly) {
  61401. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  61402. }
  61403. return this._boundingInfo.intersects(target._boundingInfo, false);
  61404. };
  61405. return SolidParticle;
  61406. }());
  61407. BABYLON.SolidParticle = SolidParticle;
  61408. /**
  61409. * Represents the shape of the model used by one particle of a solid particle system.
  61410. * SPS internal tool, don't use it manually.
  61411. */
  61412. var ModelShape = /** @class */ (function () {
  61413. /**
  61414. * 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.
  61415. * SPS internal tool, don't use it manually.
  61416. * @hidden
  61417. */
  61418. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  61419. /**
  61420. * length of the shape in the model indices array (internal use)
  61421. * @hidden
  61422. */
  61423. this._indicesLength = 0;
  61424. this.shapeID = id;
  61425. this._shape = shape;
  61426. this._indicesLength = indicesLength;
  61427. this._shapeUV = shapeUV;
  61428. this._positionFunction = posFunction;
  61429. this._vertexFunction = vtxFunction;
  61430. }
  61431. return ModelShape;
  61432. }());
  61433. BABYLON.ModelShape = ModelShape;
  61434. /**
  61435. * Represents a Depth Sorted Particle in the solid particle system.
  61436. */
  61437. var DepthSortedParticle = /** @class */ (function () {
  61438. function DepthSortedParticle() {
  61439. /**
  61440. * Index of the particle in the "indices" array
  61441. */
  61442. this.ind = 0;
  61443. /**
  61444. * Length of the particle shape in the "indices" array
  61445. */
  61446. this.indicesLength = 0;
  61447. /**
  61448. * Squared distance from the particle to the camera
  61449. */
  61450. this.sqDistance = 0.0;
  61451. }
  61452. return DepthSortedParticle;
  61453. }());
  61454. BABYLON.DepthSortedParticle = DepthSortedParticle;
  61455. })(BABYLON || (BABYLON = {}));
  61456. //# sourceMappingURL=babylon.solidParticle.js.map
  61457. var BABYLON;
  61458. (function (BABYLON) {
  61459. /**
  61460. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  61461. *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.
  61462. * The SPS is also a particle system. It provides some methods to manage the particles.
  61463. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  61464. *
  61465. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  61466. */
  61467. var SolidParticleSystem = /** @class */ (function () {
  61468. /**
  61469. * Creates a SPS (Solid Particle System) object.
  61470. * @param name (String) is the SPS name, this will be the underlying mesh name.
  61471. * @param scene (Scene) is the scene in which the SPS is added.
  61472. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  61473. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  61474. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  61475. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  61476. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  61477. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  61478. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  61479. */
  61480. function SolidParticleSystem(name, scene, options) {
  61481. /**
  61482. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  61483. * Example : var p = SPS.particles[i];
  61484. */
  61485. this.particles = new Array();
  61486. /**
  61487. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  61488. */
  61489. this.nbParticles = 0;
  61490. /**
  61491. * If the particles must ever face the camera (default false). Useful for planar particles.
  61492. */
  61493. this.billboard = false;
  61494. /**
  61495. * Recompute normals when adding a shape
  61496. */
  61497. this.recomputeNormals = true;
  61498. /**
  61499. * This a counter ofr your own usage. It's not set by any SPS functions.
  61500. */
  61501. this.counter = 0;
  61502. /**
  61503. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  61504. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  61505. */
  61506. this.vars = {};
  61507. /**
  61508. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  61509. * @hidden
  61510. */
  61511. this._bSphereOnly = false;
  61512. /**
  61513. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  61514. * @hidden
  61515. */
  61516. this._bSphereRadiusFactor = 1.0;
  61517. this._positions = new Array();
  61518. this._indices = new Array();
  61519. this._normals = new Array();
  61520. this._colors = new Array();
  61521. this._uvs = new Array();
  61522. this._index = 0; // indices index
  61523. this._updatable = true;
  61524. this._pickable = false;
  61525. this._isVisibilityBoxLocked = false;
  61526. this._alwaysVisible = false;
  61527. this._depthSort = false;
  61528. this._shapeCounter = 0;
  61529. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  61530. this._color = new BABYLON.Color4(0, 0, 0, 0);
  61531. this._computeParticleColor = true;
  61532. this._computeParticleTexture = true;
  61533. this._computeParticleRotation = true;
  61534. this._computeParticleVertex = false;
  61535. this._computeBoundingBox = false;
  61536. this._depthSortParticles = true;
  61537. this._cam_axisZ = BABYLON.Vector3.Zero();
  61538. this._cam_axisY = BABYLON.Vector3.Zero();
  61539. this._cam_axisX = BABYLON.Vector3.Zero();
  61540. this._axisZ = BABYLON.Axis.Z;
  61541. this._camDir = BABYLON.Vector3.Zero();
  61542. this._camInvertedPosition = BABYLON.Vector3.Zero();
  61543. this._rotMatrix = new BABYLON.Matrix();
  61544. this._invertMatrix = new BABYLON.Matrix();
  61545. this._rotated = BABYLON.Vector3.Zero();
  61546. this._quaternion = new BABYLON.Quaternion();
  61547. this._vertex = BABYLON.Vector3.Zero();
  61548. this._normal = BABYLON.Vector3.Zero();
  61549. this._yaw = 0.0;
  61550. this._pitch = 0.0;
  61551. this._roll = 0.0;
  61552. this._halfroll = 0.0;
  61553. this._halfpitch = 0.0;
  61554. this._halfyaw = 0.0;
  61555. this._sinRoll = 0.0;
  61556. this._cosRoll = 0.0;
  61557. this._sinPitch = 0.0;
  61558. this._cosPitch = 0.0;
  61559. this._sinYaw = 0.0;
  61560. this._cosYaw = 0.0;
  61561. this._mustUnrotateFixedNormals = false;
  61562. this._minimum = BABYLON.Vector3.Zero();
  61563. this._maximum = BABYLON.Vector3.Zero();
  61564. this._minBbox = BABYLON.Vector3.Zero();
  61565. this._maxBbox = BABYLON.Vector3.Zero();
  61566. this._particlesIntersect = false;
  61567. this._depthSortFunction = function (p1, p2) {
  61568. return (p2.sqDistance - p1.sqDistance);
  61569. };
  61570. this._needs32Bits = false;
  61571. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  61572. this._scaledPivot = BABYLON.Vector3.Zero();
  61573. this._particleHasParent = false;
  61574. this.name = name;
  61575. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61576. this._camera = scene.activeCamera;
  61577. this._pickable = options ? options.isPickable : false;
  61578. this._depthSort = options ? options.enableDepthSort : false;
  61579. this._particlesIntersect = options ? options.particleIntersection : false;
  61580. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  61581. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  61582. if (options && options.updatable !== undefined) {
  61583. this._updatable = options.updatable;
  61584. }
  61585. else {
  61586. this._updatable = true;
  61587. }
  61588. if (this._pickable) {
  61589. this.pickedParticles = [];
  61590. }
  61591. if (this._depthSort) {
  61592. this.depthSortedParticles = [];
  61593. }
  61594. }
  61595. /**
  61596. * Builds the SPS underlying mesh. Returns a standard Mesh.
  61597. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  61598. * @returns the created mesh
  61599. */
  61600. SolidParticleSystem.prototype.buildMesh = function () {
  61601. if (this.nbParticles === 0) {
  61602. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  61603. this.addShape(triangle, 1);
  61604. triangle.dispose();
  61605. }
  61606. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  61607. this._positions32 = new Float32Array(this._positions);
  61608. this._uvs32 = new Float32Array(this._uvs);
  61609. this._colors32 = new Float32Array(this._colors);
  61610. if (this.recomputeNormals) {
  61611. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  61612. }
  61613. this._normals32 = new Float32Array(this._normals);
  61614. this._fixedNormal32 = new Float32Array(this._normals);
  61615. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  61616. this._unrotateFixedNormals();
  61617. }
  61618. var vertexData = new BABYLON.VertexData();
  61619. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  61620. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  61621. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  61622. if (this._uvs32.length > 0) {
  61623. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  61624. }
  61625. if (this._colors32.length > 0) {
  61626. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  61627. }
  61628. var mesh = new BABYLON.Mesh(this.name, this._scene);
  61629. vertexData.applyToMesh(mesh, this._updatable);
  61630. this.mesh = mesh;
  61631. this.mesh.isPickable = this._pickable;
  61632. // free memory
  61633. if (!this._depthSort) {
  61634. this._indices = null;
  61635. }
  61636. this._positions = null;
  61637. this._normals = null;
  61638. this._uvs = null;
  61639. this._colors = null;
  61640. if (!this._updatable) {
  61641. this.particles.length = 0;
  61642. }
  61643. return mesh;
  61644. };
  61645. /**
  61646. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  61647. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  61648. * Thus the particles generated from `digest()` have their property `position` set yet.
  61649. * @param mesh ( Mesh ) is the mesh to be digested
  61650. * @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
  61651. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  61652. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  61653. * @returns the current SPS
  61654. */
  61655. SolidParticleSystem.prototype.digest = function (mesh, options) {
  61656. var size = (options && options.facetNb) || 1;
  61657. var number = (options && options.number) || 0;
  61658. var delta = (options && options.delta) || 0;
  61659. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61660. var meshInd = mesh.getIndices();
  61661. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61662. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61663. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61664. var f = 0; // facet counter
  61665. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  61666. // compute size from number
  61667. if (number) {
  61668. number = (number > totalFacets) ? totalFacets : number;
  61669. size = Math.round(totalFacets / number);
  61670. delta = 0;
  61671. }
  61672. else {
  61673. size = (size > totalFacets) ? totalFacets : size;
  61674. }
  61675. var facetPos = []; // submesh positions
  61676. var facetInd = []; // submesh indices
  61677. var facetUV = []; // submesh UV
  61678. var facetCol = []; // submesh colors
  61679. var barycenter = BABYLON.Vector3.Zero();
  61680. var sizeO = size;
  61681. while (f < totalFacets) {
  61682. size = sizeO + Math.floor((1 + delta) * Math.random());
  61683. if (f > totalFacets - size) {
  61684. size = totalFacets - f;
  61685. }
  61686. // reset temp arrays
  61687. facetPos.length = 0;
  61688. facetInd.length = 0;
  61689. facetUV.length = 0;
  61690. facetCol.length = 0;
  61691. // iterate over "size" facets
  61692. var fi = 0;
  61693. for (var j = f * 3; j < (f + size) * 3; j++) {
  61694. facetInd.push(fi);
  61695. var i = meshInd[j];
  61696. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  61697. if (meshUV) {
  61698. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  61699. }
  61700. if (meshCol) {
  61701. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  61702. }
  61703. fi++;
  61704. }
  61705. // create a model shape for each single particle
  61706. var idx = this.nbParticles;
  61707. var shape = this._posToShape(facetPos);
  61708. var shapeUV = this._uvsToShapeUV(facetUV);
  61709. // compute the barycenter of the shape
  61710. var v;
  61711. for (v = 0; v < shape.length; v++) {
  61712. barycenter.addInPlace(shape[v]);
  61713. }
  61714. barycenter.scaleInPlace(1 / shape.length);
  61715. // shift the shape from its barycenter to the origin
  61716. for (v = 0; v < shape.length; v++) {
  61717. shape[v].subtractInPlace(barycenter);
  61718. }
  61719. var bInfo;
  61720. if (this._particlesIntersect) {
  61721. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  61722. }
  61723. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  61724. // add the particle in the SPS
  61725. var currentPos = this._positions.length;
  61726. var currentInd = this._indices.length;
  61727. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  61728. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  61729. // initialize the particle position
  61730. this.particles[this.nbParticles].position.addInPlace(barycenter);
  61731. this._index += shape.length;
  61732. idx++;
  61733. this.nbParticles++;
  61734. this._shapeCounter++;
  61735. f += size;
  61736. }
  61737. return this;
  61738. };
  61739. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  61740. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  61741. var index = 0;
  61742. var idx = 0;
  61743. for (var p = 0; p < this.particles.length; p++) {
  61744. this._particle = this.particles[p];
  61745. this._shape = this._particle._model._shape;
  61746. if (this._particle.rotationQuaternion) {
  61747. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61748. }
  61749. else {
  61750. this._yaw = this._particle.rotation.y;
  61751. this._pitch = this._particle.rotation.x;
  61752. this._roll = this._particle.rotation.z;
  61753. this._quaternionRotationYPR();
  61754. }
  61755. this._quaternionToRotationMatrix();
  61756. this._rotMatrix.invertToRef(this._invertMatrix);
  61757. for (var pt = 0; pt < this._shape.length; pt++) {
  61758. idx = index + pt * 3;
  61759. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  61760. this._fixedNormal32[idx] = this._normal.x;
  61761. this._fixedNormal32[idx + 1] = this._normal.y;
  61762. this._fixedNormal32[idx + 2] = this._normal.z;
  61763. }
  61764. index = idx + 3;
  61765. }
  61766. };
  61767. //reset copy
  61768. SolidParticleSystem.prototype._resetCopy = function () {
  61769. this._copy.position.x = 0;
  61770. this._copy.position.y = 0;
  61771. this._copy.position.z = 0;
  61772. this._copy.rotation.x = 0;
  61773. this._copy.rotation.y = 0;
  61774. this._copy.rotation.z = 0;
  61775. this._copy.rotationQuaternion = null;
  61776. this._copy.scaling.x = 1.0;
  61777. this._copy.scaling.y = 1.0;
  61778. this._copy.scaling.z = 1.0;
  61779. this._copy.uvs.x = 0;
  61780. this._copy.uvs.y = 0;
  61781. this._copy.uvs.z = 1.0;
  61782. this._copy.uvs.w = 1.0;
  61783. this._copy.color = null;
  61784. this._copy.translateFromPivot = false;
  61785. };
  61786. // _meshBuilder : inserts the shape model in the global SPS mesh
  61787. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  61788. var i;
  61789. var u = 0;
  61790. var c = 0;
  61791. var n = 0;
  61792. this._resetCopy();
  61793. if (options && options.positionFunction) { // call to custom positionFunction
  61794. options.positionFunction(this._copy, idx, idxInShape);
  61795. this._mustUnrotateFixedNormals = true;
  61796. }
  61797. if (this._copy.rotationQuaternion) {
  61798. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61799. }
  61800. else {
  61801. this._yaw = this._copy.rotation.y;
  61802. this._pitch = this._copy.rotation.x;
  61803. this._roll = this._copy.rotation.z;
  61804. this._quaternionRotationYPR();
  61805. }
  61806. this._quaternionToRotationMatrix();
  61807. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  61808. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  61809. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  61810. if (this._copy.translateFromPivot) {
  61811. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61812. }
  61813. else {
  61814. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61815. }
  61816. for (i = 0; i < shape.length; i++) {
  61817. this._vertex.x = shape[i].x;
  61818. this._vertex.y = shape[i].y;
  61819. this._vertex.z = shape[i].z;
  61820. if (options && options.vertexFunction) {
  61821. options.vertexFunction(this._copy, this._vertex, i);
  61822. }
  61823. this._vertex.x *= this._copy.scaling.x;
  61824. this._vertex.y *= this._copy.scaling.y;
  61825. this._vertex.z *= this._copy.scaling.z;
  61826. this._vertex.x -= this._scaledPivot.x;
  61827. this._vertex.y -= this._scaledPivot.y;
  61828. this._vertex.z -= this._scaledPivot.z;
  61829. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61830. this._rotated.addInPlace(this._pivotBackTranslation);
  61831. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  61832. if (meshUV) {
  61833. 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);
  61834. u += 2;
  61835. }
  61836. if (this._copy.color) {
  61837. this._color = this._copy.color;
  61838. }
  61839. else if (meshCol && meshCol[c] !== undefined) {
  61840. this._color.r = meshCol[c];
  61841. this._color.g = meshCol[c + 1];
  61842. this._color.b = meshCol[c + 2];
  61843. this._color.a = meshCol[c + 3];
  61844. }
  61845. else {
  61846. this._color.r = 1.0;
  61847. this._color.g = 1.0;
  61848. this._color.b = 1.0;
  61849. this._color.a = 1.0;
  61850. }
  61851. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  61852. c += 4;
  61853. if (!this.recomputeNormals && meshNor) {
  61854. this._normal.x = meshNor[n];
  61855. this._normal.y = meshNor[n + 1];
  61856. this._normal.z = meshNor[n + 2];
  61857. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  61858. normals.push(this._normal.x, this._normal.y, this._normal.z);
  61859. n += 3;
  61860. }
  61861. }
  61862. for (i = 0; i < meshInd.length; i++) {
  61863. var current_ind = p + meshInd[i];
  61864. indices.push(current_ind);
  61865. if (current_ind > 65535) {
  61866. this._needs32Bits = true;
  61867. }
  61868. }
  61869. if (this._pickable) {
  61870. var nbfaces = meshInd.length / 3;
  61871. for (i = 0; i < nbfaces; i++) {
  61872. this.pickedParticles.push({ idx: idx, faceId: i });
  61873. }
  61874. }
  61875. if (this._depthSort) {
  61876. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  61877. }
  61878. return this._copy;
  61879. };
  61880. // returns a shape array from positions array
  61881. SolidParticleSystem.prototype._posToShape = function (positions) {
  61882. var shape = [];
  61883. for (var i = 0; i < positions.length; i += 3) {
  61884. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  61885. }
  61886. return shape;
  61887. };
  61888. // returns a shapeUV array from a Vector4 uvs
  61889. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  61890. var shapeUV = [];
  61891. if (uvs) {
  61892. for (var i = 0; i < uvs.length; i++)
  61893. shapeUV.push(uvs[i]);
  61894. }
  61895. return shapeUV;
  61896. };
  61897. // adds a new particle object in the particles array
  61898. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  61899. if (bInfo === void 0) { bInfo = null; }
  61900. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  61901. this.particles.push(sp);
  61902. return sp;
  61903. };
  61904. /**
  61905. * Adds some particles to the SPS from the model shape. Returns the shape id.
  61906. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  61907. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  61908. * @param nb (positive integer) the number of particles to be created from this model
  61909. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  61910. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  61911. * @returns the number of shapes in the system
  61912. */
  61913. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  61914. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61915. var meshInd = mesh.getIndices();
  61916. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61917. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61918. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61919. var bbInfo;
  61920. if (this._particlesIntersect) {
  61921. bbInfo = mesh.getBoundingInfo();
  61922. }
  61923. var shape = this._posToShape(meshPos);
  61924. var shapeUV = this._uvsToShapeUV(meshUV);
  61925. var posfunc = options ? options.positionFunction : null;
  61926. var vtxfunc = options ? options.vertexFunction : null;
  61927. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  61928. // particles
  61929. var sp;
  61930. var currentCopy;
  61931. var idx = this.nbParticles;
  61932. for (var i = 0; i < nb; i++) {
  61933. var currentPos = this._positions.length;
  61934. var currentInd = this._indices.length;
  61935. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  61936. if (this._updatable) {
  61937. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  61938. sp.position.copyFrom(currentCopy.position);
  61939. sp.rotation.copyFrom(currentCopy.rotation);
  61940. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  61941. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  61942. }
  61943. if (currentCopy.color && sp.color) {
  61944. sp.color.copyFrom(currentCopy.color);
  61945. }
  61946. sp.scaling.copyFrom(currentCopy.scaling);
  61947. sp.uvs.copyFrom(currentCopy.uvs);
  61948. }
  61949. this._index += shape.length;
  61950. idx++;
  61951. }
  61952. this.nbParticles += nb;
  61953. this._shapeCounter++;
  61954. return this._shapeCounter - 1;
  61955. };
  61956. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  61957. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  61958. this._resetCopy();
  61959. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  61960. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  61961. }
  61962. if (this._copy.rotationQuaternion) {
  61963. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61964. }
  61965. else {
  61966. this._yaw = this._copy.rotation.y;
  61967. this._pitch = this._copy.rotation.x;
  61968. this._roll = this._copy.rotation.z;
  61969. this._quaternionRotationYPR();
  61970. }
  61971. this._quaternionToRotationMatrix();
  61972. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61973. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61974. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61975. if (this._copy.translateFromPivot) {
  61976. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61977. }
  61978. else {
  61979. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61980. }
  61981. this._shape = particle._model._shape;
  61982. for (var pt = 0; pt < this._shape.length; pt++) {
  61983. this._vertex.x = this._shape[pt].x;
  61984. this._vertex.y = this._shape[pt].y;
  61985. this._vertex.z = this._shape[pt].z;
  61986. if (particle._model._vertexFunction) {
  61987. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  61988. }
  61989. this._vertex.x *= this._copy.scaling.x;
  61990. this._vertex.y *= this._copy.scaling.y;
  61991. this._vertex.z *= this._copy.scaling.z;
  61992. this._vertex.x -= this._scaledPivot.x;
  61993. this._vertex.y -= this._scaledPivot.y;
  61994. this._vertex.z -= this._scaledPivot.z;
  61995. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61996. this._rotated.addInPlace(this._pivotBackTranslation);
  61997. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  61998. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  61999. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  62000. }
  62001. particle.position.x = 0.0;
  62002. particle.position.y = 0.0;
  62003. particle.position.z = 0.0;
  62004. particle.rotation.x = 0.0;
  62005. particle.rotation.y = 0.0;
  62006. particle.rotation.z = 0.0;
  62007. particle.rotationQuaternion = null;
  62008. particle.scaling.x = 1.0;
  62009. particle.scaling.y = 1.0;
  62010. particle.scaling.z = 1.0;
  62011. particle.uvs.x = 0.0;
  62012. particle.uvs.y = 0.0;
  62013. particle.uvs.z = 1.0;
  62014. particle.uvs.w = 1.0;
  62015. particle.pivot.x = 0.0;
  62016. particle.pivot.y = 0.0;
  62017. particle.pivot.z = 0.0;
  62018. particle.translateFromPivot = false;
  62019. particle.parentId = null;
  62020. };
  62021. /**
  62022. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  62023. * @returns the SPS.
  62024. */
  62025. SolidParticleSystem.prototype.rebuildMesh = function () {
  62026. for (var p = 0; p < this.particles.length; p++) {
  62027. this._rebuildParticle(this.particles[p]);
  62028. }
  62029. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62030. return this;
  62031. };
  62032. /**
  62033. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  62034. * This method calls `updateParticle()` for each particle of the SPS.
  62035. * For an animated SPS, it is usually called within the render loop.
  62036. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  62037. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  62038. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  62039. * @returns the SPS.
  62040. */
  62041. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  62042. if (start === void 0) { start = 0; }
  62043. if (end === void 0) { end = this.nbParticles - 1; }
  62044. if (update === void 0) { update = true; }
  62045. if (!this._updatable) {
  62046. return this;
  62047. }
  62048. // custom beforeUpdate
  62049. this.beforeUpdateParticles(start, end, update);
  62050. this._cam_axisX.x = 1.0;
  62051. this._cam_axisX.y = 0.0;
  62052. this._cam_axisX.z = 0.0;
  62053. this._cam_axisY.x = 0.0;
  62054. this._cam_axisY.y = 1.0;
  62055. this._cam_axisY.z = 0.0;
  62056. this._cam_axisZ.x = 0.0;
  62057. this._cam_axisZ.y = 0.0;
  62058. this._cam_axisZ.z = 1.0;
  62059. // cases when the World Matrix is to be computed first
  62060. if (this.billboard || this._depthSort) {
  62061. this.mesh.computeWorldMatrix(true);
  62062. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  62063. }
  62064. // if the particles will always face the camera
  62065. if (this.billboard) {
  62066. // compute the camera position and un-rotate it by the current mesh rotation
  62067. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  62068. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  62069. this._cam_axisZ.normalize();
  62070. // same for camera up vector extracted from the cam view matrix
  62071. var view = this._camera.getViewMatrix(true);
  62072. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  62073. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  62074. this._cam_axisY.normalize();
  62075. this._cam_axisX.normalize();
  62076. }
  62077. // if depthSort, compute the camera global position in the mesh local system
  62078. if (this._depthSort) {
  62079. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  62080. }
  62081. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  62082. var idx = 0; // current position index in the global array positions32
  62083. var index = 0; // position start index in the global array positions32 of the current particle
  62084. var colidx = 0; // current color index in the global array colors32
  62085. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  62086. var uvidx = 0; // current uv index in the global array uvs32
  62087. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  62088. var pt = 0; // current index in the particle model shape
  62089. if (this.mesh.isFacetDataEnabled) {
  62090. this._computeBoundingBox = true;
  62091. }
  62092. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  62093. if (this._computeBoundingBox) {
  62094. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  62095. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  62096. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  62097. }
  62098. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  62099. if (this.mesh._boundingInfo) {
  62100. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  62101. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  62102. }
  62103. }
  62104. }
  62105. // particle loop
  62106. index = this.particles[start]._pos;
  62107. var vpos = (index / 3) | 0;
  62108. colorIndex = vpos * 4;
  62109. uvIndex = vpos * 2;
  62110. for (var p = start; p <= end; p++) {
  62111. this._particle = this.particles[p];
  62112. this._shape = this._particle._model._shape;
  62113. this._shapeUV = this._particle._model._shapeUV;
  62114. // call to custom user function to update the particle properties
  62115. this.updateParticle(this._particle);
  62116. // camera-particle distance for depth sorting
  62117. if (this._depthSort && this._depthSortParticles) {
  62118. var dsp = this.depthSortedParticles[p];
  62119. dsp.ind = this._particle._ind;
  62120. dsp.indicesLength = this._particle._model._indicesLength;
  62121. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  62122. }
  62123. // skip the computations for inactive or already invisible particles
  62124. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  62125. // increment indexes for the next particle
  62126. pt = this._shape.length;
  62127. index += pt * 3;
  62128. colorIndex += pt * 4;
  62129. uvIndex += pt * 2;
  62130. continue;
  62131. }
  62132. if (this._particle.isVisible) {
  62133. this._particle._stillInvisible = false; // un-mark permanent invisibility
  62134. this._particleHasParent = (this._particle.parentId !== null);
  62135. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62136. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62137. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62138. // particle rotation matrix
  62139. if (this.billboard) {
  62140. this._particle.rotation.x = 0.0;
  62141. this._particle.rotation.y = 0.0;
  62142. }
  62143. if (this._computeParticleRotation || this.billboard) {
  62144. if (this._particle.rotationQuaternion) {
  62145. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62146. }
  62147. else {
  62148. this._yaw = this._particle.rotation.y;
  62149. this._pitch = this._particle.rotation.x;
  62150. this._roll = this._particle.rotation.z;
  62151. this._quaternionRotationYPR();
  62152. }
  62153. this._quaternionToRotationMatrix();
  62154. }
  62155. if (this._particleHasParent) {
  62156. this._parent = this.particles[this._particle.parentId];
  62157. 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];
  62158. 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];
  62159. 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];
  62160. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  62161. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  62162. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  62163. if (this._computeParticleRotation || this.billboard) {
  62164. 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];
  62165. 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];
  62166. 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];
  62167. 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];
  62168. 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];
  62169. 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];
  62170. 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];
  62171. 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];
  62172. 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];
  62173. }
  62174. }
  62175. else {
  62176. this._particle._globalPosition.x = this._particle.position.x;
  62177. this._particle._globalPosition.y = this._particle.position.y;
  62178. this._particle._globalPosition.z = this._particle.position.z;
  62179. if (this._computeParticleRotation || this.billboard) {
  62180. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  62181. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  62182. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  62183. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  62184. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  62185. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  62186. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  62187. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  62188. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  62189. }
  62190. }
  62191. if (this._particle.translateFromPivot) {
  62192. this._pivotBackTranslation.x = 0.0;
  62193. this._pivotBackTranslation.y = 0.0;
  62194. this._pivotBackTranslation.z = 0.0;
  62195. }
  62196. else {
  62197. this._pivotBackTranslation.x = this._scaledPivot.x;
  62198. this._pivotBackTranslation.y = this._scaledPivot.y;
  62199. this._pivotBackTranslation.z = this._scaledPivot.z;
  62200. }
  62201. // particle vertex loop
  62202. for (pt = 0; pt < this._shape.length; pt++) {
  62203. idx = index + pt * 3;
  62204. colidx = colorIndex + pt * 4;
  62205. uvidx = uvIndex + pt * 2;
  62206. this._vertex.x = this._shape[pt].x;
  62207. this._vertex.y = this._shape[pt].y;
  62208. this._vertex.z = this._shape[pt].z;
  62209. if (this._computeParticleVertex) {
  62210. this.updateParticleVertex(this._particle, this._vertex, pt);
  62211. }
  62212. // positions
  62213. this._vertex.x *= this._particle.scaling.x;
  62214. this._vertex.y *= this._particle.scaling.y;
  62215. this._vertex.z *= this._particle.scaling.z;
  62216. this._vertex.x -= this._scaledPivot.x;
  62217. this._vertex.y -= this._scaledPivot.y;
  62218. this._vertex.z -= this._scaledPivot.z;
  62219. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62220. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62221. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62222. this._rotated.x += this._pivotBackTranslation.x;
  62223. this._rotated.y += this._pivotBackTranslation.y;
  62224. this._rotated.z += this._pivotBackTranslation.z;
  62225. 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;
  62226. 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;
  62227. 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;
  62228. if (this._computeBoundingBox) {
  62229. if (this._positions32[idx] < this._minimum.x) {
  62230. this._minimum.x = this._positions32[idx];
  62231. }
  62232. if (this._positions32[idx] > this._maximum.x) {
  62233. this._maximum.x = this._positions32[idx];
  62234. }
  62235. if (this._positions32[idx + 1] < this._minimum.y) {
  62236. this._minimum.y = this._positions32[idx + 1];
  62237. }
  62238. if (this._positions32[idx + 1] > this._maximum.y) {
  62239. this._maximum.y = this._positions32[idx + 1];
  62240. }
  62241. if (this._positions32[idx + 2] < this._minimum.z) {
  62242. this._minimum.z = this._positions32[idx + 2];
  62243. }
  62244. if (this._positions32[idx + 2] > this._maximum.z) {
  62245. this._maximum.z = this._positions32[idx + 2];
  62246. }
  62247. }
  62248. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  62249. if (!this._computeParticleVertex) {
  62250. this._normal.x = this._fixedNormal32[idx];
  62251. this._normal.y = this._fixedNormal32[idx + 1];
  62252. this._normal.z = this._fixedNormal32[idx + 2];
  62253. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  62254. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  62255. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  62256. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62257. 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;
  62258. 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;
  62259. }
  62260. if (this._computeParticleColor && this._particle.color) {
  62261. this._colors32[colidx] = this._particle.color.r;
  62262. this._colors32[colidx + 1] = this._particle.color.g;
  62263. this._colors32[colidx + 2] = this._particle.color.b;
  62264. this._colors32[colidx + 3] = this._particle.color.a;
  62265. }
  62266. if (this._computeParticleTexture) {
  62267. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62268. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62269. }
  62270. }
  62271. }
  62272. // particle just set invisible : scaled to zero and positioned at the origin
  62273. else {
  62274. this._particle._stillInvisible = true; // mark the particle as invisible
  62275. for (pt = 0; pt < this._shape.length; pt++) {
  62276. idx = index + pt * 3;
  62277. colidx = colorIndex + pt * 4;
  62278. uvidx = uvIndex + pt * 2;
  62279. this._positions32[idx] = 0.0;
  62280. this._positions32[idx + 1] = 0.0;
  62281. this._positions32[idx + 2] = 0.0;
  62282. this._normals32[idx] = 0.0;
  62283. this._normals32[idx + 1] = 0.0;
  62284. this._normals32[idx + 2] = 0.0;
  62285. if (this._computeParticleColor && this._particle.color) {
  62286. this._colors32[colidx] = this._particle.color.r;
  62287. this._colors32[colidx + 1] = this._particle.color.g;
  62288. this._colors32[colidx + 2] = this._particle.color.b;
  62289. this._colors32[colidx + 3] = this._particle.color.a;
  62290. }
  62291. if (this._computeParticleTexture) {
  62292. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62293. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62294. }
  62295. }
  62296. }
  62297. // if the particle intersections must be computed : update the bbInfo
  62298. if (this._particlesIntersect) {
  62299. var bInfo = this._particle._boundingInfo;
  62300. var bBox = bInfo.boundingBox;
  62301. var bSphere = bInfo.boundingSphere;
  62302. if (!this._bSphereOnly) {
  62303. // place, scale and rotate the particle bbox within the SPS local system, then update it
  62304. for (var b = 0; b < bBox.vectors.length; b++) {
  62305. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  62306. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  62307. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  62308. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62309. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62310. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62311. 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;
  62312. 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;
  62313. 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;
  62314. }
  62315. bBox._update(this.mesh._worldMatrix);
  62316. }
  62317. // place and scale the particle bouding sphere in the SPS local system, then update it
  62318. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  62319. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  62320. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  62321. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  62322. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  62323. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  62324. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  62325. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  62326. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  62327. 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));
  62328. bSphere._update(this.mesh._worldMatrix);
  62329. }
  62330. // increment indexes for the next particle
  62331. index = idx + 3;
  62332. colorIndex = colidx + 4;
  62333. uvIndex = uvidx + 2;
  62334. }
  62335. // if the VBO must be updated
  62336. if (update) {
  62337. if (this._computeParticleColor) {
  62338. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  62339. }
  62340. if (this._computeParticleTexture) {
  62341. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  62342. }
  62343. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62344. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  62345. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  62346. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  62347. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  62348. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  62349. for (var i = 0; i < this._normals32.length; i++) {
  62350. this._fixedNormal32[i] = this._normals32[i];
  62351. }
  62352. }
  62353. if (!this.mesh.areNormalsFrozen) {
  62354. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  62355. }
  62356. }
  62357. if (this._depthSort && this._depthSortParticles) {
  62358. this.depthSortedParticles.sort(this._depthSortFunction);
  62359. var dspl = this.depthSortedParticles.length;
  62360. var sorted = 0;
  62361. var lind = 0;
  62362. var sind = 0;
  62363. var sid = 0;
  62364. for (sorted = 0; sorted < dspl; sorted++) {
  62365. lind = this.depthSortedParticles[sorted].indicesLength;
  62366. sind = this.depthSortedParticles[sorted].ind;
  62367. for (var i = 0; i < lind; i++) {
  62368. this._indices32[sid] = this._indices[sind + i];
  62369. sid++;
  62370. }
  62371. }
  62372. this.mesh.updateIndices(this._indices32);
  62373. }
  62374. }
  62375. if (this._computeBoundingBox) {
  62376. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  62377. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  62378. }
  62379. this.afterUpdateParticles(start, end, update);
  62380. return this;
  62381. };
  62382. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  62383. this._halfroll = this._roll * 0.5;
  62384. this._halfpitch = this._pitch * 0.5;
  62385. this._halfyaw = this._yaw * 0.5;
  62386. this._sinRoll = Math.sin(this._halfroll);
  62387. this._cosRoll = Math.cos(this._halfroll);
  62388. this._sinPitch = Math.sin(this._halfpitch);
  62389. this._cosPitch = Math.cos(this._halfpitch);
  62390. this._sinYaw = Math.sin(this._halfyaw);
  62391. this._cosYaw = Math.cos(this._halfyaw);
  62392. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  62393. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  62394. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  62395. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  62396. };
  62397. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  62398. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  62399. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  62400. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  62401. this._rotMatrix.m[3] = 0;
  62402. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  62403. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  62404. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  62405. this._rotMatrix.m[7] = 0;
  62406. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  62407. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  62408. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  62409. this._rotMatrix.m[11] = 0;
  62410. this._rotMatrix.m[12] = 0;
  62411. this._rotMatrix.m[13] = 0;
  62412. this._rotMatrix.m[14] = 0;
  62413. this._rotMatrix.m[15] = 1.0;
  62414. };
  62415. /**
  62416. * Disposes the SPS.
  62417. */
  62418. SolidParticleSystem.prototype.dispose = function () {
  62419. this.mesh.dispose();
  62420. this.vars = null;
  62421. // drop references to internal big arrays for the GC
  62422. this._positions = null;
  62423. this._indices = null;
  62424. this._normals = null;
  62425. this._uvs = null;
  62426. this._colors = null;
  62427. this._indices32 = null;
  62428. this._positions32 = null;
  62429. this._normals32 = null;
  62430. this._fixedNormal32 = null;
  62431. this._uvs32 = null;
  62432. this._colors32 = null;
  62433. this.pickedParticles = null;
  62434. };
  62435. /**
  62436. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  62437. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62438. * @returns the SPS.
  62439. */
  62440. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  62441. if (!this._isVisibilityBoxLocked) {
  62442. this.mesh.refreshBoundingInfo();
  62443. }
  62444. return this;
  62445. };
  62446. /**
  62447. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  62448. * @param size the size (float) of the visibility box
  62449. * note : this doesn't lock the SPS mesh bounding box.
  62450. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62451. */
  62452. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  62453. var vis = size / 2;
  62454. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  62455. };
  62456. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  62457. /**
  62458. * Gets whether the SPS as always visible or not
  62459. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62460. */
  62461. get: function () {
  62462. return this._alwaysVisible;
  62463. },
  62464. /**
  62465. * Sets the SPS as always visible or not
  62466. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62467. */
  62468. set: function (val) {
  62469. this._alwaysVisible = val;
  62470. this.mesh.alwaysSelectAsActiveMesh = val;
  62471. },
  62472. enumerable: true,
  62473. configurable: true
  62474. });
  62475. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  62476. /**
  62477. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62478. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62479. */
  62480. get: function () {
  62481. return this._isVisibilityBoxLocked;
  62482. },
  62483. /**
  62484. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62485. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62486. */
  62487. set: function (val) {
  62488. this._isVisibilityBoxLocked = val;
  62489. var boundingInfo = this.mesh.getBoundingInfo();
  62490. boundingInfo.isLocked = val;
  62491. },
  62492. enumerable: true,
  62493. configurable: true
  62494. });
  62495. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  62496. /**
  62497. * Gets if `setParticles()` computes the particle rotations or not.
  62498. * Default value : true. The SPS is faster when it's set to false.
  62499. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62500. */
  62501. get: function () {
  62502. return this._computeParticleRotation;
  62503. },
  62504. /**
  62505. * Tells to `setParticles()` to compute the particle rotations or not.
  62506. * Default value : true. The SPS is faster when it's set to false.
  62507. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62508. */
  62509. set: function (val) {
  62510. this._computeParticleRotation = val;
  62511. },
  62512. enumerable: true,
  62513. configurable: true
  62514. });
  62515. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  62516. /**
  62517. * Gets if `setParticles()` computes the particle colors or not.
  62518. * Default value : true. The SPS is faster when it's set to false.
  62519. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62520. */
  62521. get: function () {
  62522. return this._computeParticleColor;
  62523. },
  62524. /**
  62525. * Tells to `setParticles()` to compute the particle colors or not.
  62526. * Default value : true. The SPS is faster when it's set to false.
  62527. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62528. */
  62529. set: function (val) {
  62530. this._computeParticleColor = val;
  62531. },
  62532. enumerable: true,
  62533. configurable: true
  62534. });
  62535. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  62536. /**
  62537. * Gets if `setParticles()` computes the particle textures or not.
  62538. * Default value : true. The SPS is faster when it's set to false.
  62539. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  62540. */
  62541. get: function () {
  62542. return this._computeParticleTexture;
  62543. },
  62544. set: function (val) {
  62545. this._computeParticleTexture = val;
  62546. },
  62547. enumerable: true,
  62548. configurable: true
  62549. });
  62550. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  62551. /**
  62552. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  62553. * Default value : false. The SPS is faster when it's set to false.
  62554. * Note : the particle custom vertex positions aren't stored values.
  62555. */
  62556. get: function () {
  62557. return this._computeParticleVertex;
  62558. },
  62559. /**
  62560. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  62561. * Default value : false. The SPS is faster when it's set to false.
  62562. * Note : the particle custom vertex positions aren't stored values.
  62563. */
  62564. set: function (val) {
  62565. this._computeParticleVertex = val;
  62566. },
  62567. enumerable: true,
  62568. configurable: true
  62569. });
  62570. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  62571. /**
  62572. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  62573. */
  62574. get: function () {
  62575. return this._computeBoundingBox;
  62576. },
  62577. /**
  62578. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  62579. */
  62580. set: function (val) {
  62581. this._computeBoundingBox = val;
  62582. },
  62583. enumerable: true,
  62584. configurable: true
  62585. });
  62586. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  62587. /**
  62588. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  62589. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62590. * Default : `true`
  62591. */
  62592. get: function () {
  62593. return this._depthSortParticles;
  62594. },
  62595. /**
  62596. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  62597. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62598. * Default : `true`
  62599. */
  62600. set: function (val) {
  62601. this._depthSortParticles = val;
  62602. },
  62603. enumerable: true,
  62604. configurable: true
  62605. });
  62606. // =======================================================================
  62607. // Particle behavior logic
  62608. // these following methods may be overwritten by the user to fit his needs
  62609. /**
  62610. * This function does nothing. It may be overwritten to set all the particle first values.
  62611. * The SPS doesn't call this function, you may have to call it by your own.
  62612. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62613. */
  62614. SolidParticleSystem.prototype.initParticles = function () {
  62615. };
  62616. /**
  62617. * This function does nothing. It may be overwritten to recycle a particle.
  62618. * The SPS doesn't call this function, you may have to call it by your own.
  62619. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62620. * @param particle The particle to recycle
  62621. * @returns the recycled particle
  62622. */
  62623. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  62624. return particle;
  62625. };
  62626. /**
  62627. * Updates a particle : this function should be overwritten by the user.
  62628. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  62629. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62630. * @example : just set a particle position or velocity and recycle conditions
  62631. * @param particle The particle to update
  62632. * @returns the updated particle
  62633. */
  62634. SolidParticleSystem.prototype.updateParticle = function (particle) {
  62635. return particle;
  62636. };
  62637. /**
  62638. * Updates a vertex of a particle : it can be overwritten by the user.
  62639. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  62640. * @param particle the current particle
  62641. * @param vertex the current index of the current particle
  62642. * @param pt the index of the current vertex in the particle shape
  62643. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  62644. * @example : just set a vertex particle position
  62645. * @returns the updated vertex
  62646. */
  62647. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  62648. return vertex;
  62649. };
  62650. /**
  62651. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  62652. * This does nothing and may be overwritten by the user.
  62653. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62654. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62655. * @param update the boolean update value actually passed to setParticles()
  62656. */
  62657. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  62658. };
  62659. /**
  62660. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  62661. * This will be passed three parameters.
  62662. * This does nothing and may be overwritten by the user.
  62663. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62664. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62665. * @param update the boolean update value actually passed to setParticles()
  62666. */
  62667. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  62668. };
  62669. return SolidParticleSystem;
  62670. }());
  62671. BABYLON.SolidParticleSystem = SolidParticleSystem;
  62672. })(BABYLON || (BABYLON = {}));
  62673. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  62674. var BABYLON;
  62675. (function (BABYLON) {
  62676. /**
  62677. * Class containing static functions to help procedurally build meshes
  62678. */
  62679. var MeshBuilder = /** @class */ (function () {
  62680. function MeshBuilder() {
  62681. }
  62682. MeshBuilder.updateSideOrientation = function (orientation) {
  62683. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62684. return BABYLON.Mesh.DOUBLESIDE;
  62685. }
  62686. if (orientation === undefined || orientation === null) {
  62687. return BABYLON.Mesh.FRONTSIDE;
  62688. }
  62689. return orientation;
  62690. };
  62691. /**
  62692. * Creates a box mesh
  62693. * * The parameter `size` sets the size (float) of each box side (default 1)
  62694. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  62695. * * 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)
  62696. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62697. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62698. * * 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
  62699. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62700. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  62701. * @param name defines the name of the mesh
  62702. * @param options defines the options used to create the mesh
  62703. * @param scene defines the hosting scene
  62704. * @returns the box mesh
  62705. */
  62706. MeshBuilder.CreateBox = function (name, options, scene) {
  62707. if (scene === void 0) { scene = null; }
  62708. var box = new BABYLON.Mesh(name, scene);
  62709. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62710. box._originalBuilderSideOrientation = options.sideOrientation;
  62711. var vertexData = BABYLON.VertexData.CreateBox(options);
  62712. vertexData.applyToMesh(box, options.updatable);
  62713. return box;
  62714. };
  62715. /**
  62716. * Creates a sphere mesh
  62717. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  62718. * * 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`)
  62719. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  62720. * * 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
  62721. * * 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)
  62722. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62723. * * 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
  62724. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62725. * @param name defines the name of the mesh
  62726. * @param options defines the options used to create the mesh
  62727. * @param scene defines the hosting scene
  62728. * @returns the sphere mesh
  62729. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  62730. */
  62731. MeshBuilder.CreateSphere = function (name, options, scene) {
  62732. var sphere = new BABYLON.Mesh(name, scene);
  62733. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62734. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62735. var vertexData = BABYLON.VertexData.CreateSphere(options);
  62736. vertexData.applyToMesh(sphere, options.updatable);
  62737. return sphere;
  62738. };
  62739. /**
  62740. * Creates a plane polygonal mesh. By default, this is a disc
  62741. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  62742. * * 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
  62743. * * 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
  62744. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62745. * * 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
  62746. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62747. * @param name defines the name of the mesh
  62748. * @param options defines the options used to create the mesh
  62749. * @param scene defines the hosting scene
  62750. * @returns the plane polygonal mesh
  62751. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  62752. */
  62753. MeshBuilder.CreateDisc = function (name, options, scene) {
  62754. if (scene === void 0) { scene = null; }
  62755. var disc = new BABYLON.Mesh(name, scene);
  62756. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62757. disc._originalBuilderSideOrientation = options.sideOrientation;
  62758. var vertexData = BABYLON.VertexData.CreateDisc(options);
  62759. vertexData.applyToMesh(disc, options.updatable);
  62760. return disc;
  62761. };
  62762. /**
  62763. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  62764. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  62765. * * 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`)
  62766. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  62767. * * 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
  62768. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62769. * * 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
  62770. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62771. * @param name defines the name of the mesh
  62772. * @param options defines the options used to create the mesh
  62773. * @param scene defines the hosting scene
  62774. * @returns the icosahedron mesh
  62775. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  62776. */
  62777. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  62778. var sphere = new BABYLON.Mesh(name, scene);
  62779. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62780. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62781. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  62782. vertexData.applyToMesh(sphere, options.updatable);
  62783. return sphere;
  62784. };
  62785. ;
  62786. /**
  62787. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62788. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  62789. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  62790. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  62791. * * 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
  62792. * * 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
  62793. * * 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
  62794. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62795. * * 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
  62796. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62797. * * 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
  62798. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  62799. * * 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
  62800. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  62801. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62802. * @param name defines the name of the mesh
  62803. * @param options defines the options used to create the mesh
  62804. * @param scene defines the hosting scene
  62805. * @returns the ribbon mesh
  62806. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  62807. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62808. */
  62809. MeshBuilder.CreateRibbon = function (name, options, scene) {
  62810. if (scene === void 0) { scene = null; }
  62811. var pathArray = options.pathArray;
  62812. var closeArray = options.closeArray;
  62813. var closePath = options.closePath;
  62814. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62815. var instance = options.instance;
  62816. var updatable = options.updatable;
  62817. if (instance) { // existing ribbon instance update
  62818. // positionFunction : ribbon case
  62819. // only pathArray and sideOrientation parameters are taken into account for positions update
  62820. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  62821. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  62822. var positionFunction = function (positions) {
  62823. var minlg = pathArray[0].length;
  62824. var i = 0;
  62825. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  62826. for (var si = 1; si <= ns; si++) {
  62827. for (var p = 0; p < pathArray.length; p++) {
  62828. var path = pathArray[p];
  62829. var l = path.length;
  62830. minlg = (minlg < l) ? minlg : l;
  62831. var j = 0;
  62832. while (j < minlg) {
  62833. positions[i] = path[j].x;
  62834. positions[i + 1] = path[j].y;
  62835. positions[i + 2] = path[j].z;
  62836. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  62837. BABYLON.Tmp.Vector3[0].x = path[j].x;
  62838. }
  62839. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  62840. BABYLON.Tmp.Vector3[1].x = path[j].x;
  62841. }
  62842. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  62843. BABYLON.Tmp.Vector3[0].y = path[j].y;
  62844. }
  62845. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  62846. BABYLON.Tmp.Vector3[1].y = path[j].y;
  62847. }
  62848. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  62849. BABYLON.Tmp.Vector3[0].z = path[j].z;
  62850. }
  62851. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  62852. BABYLON.Tmp.Vector3[1].z = path[j].z;
  62853. }
  62854. j++;
  62855. i += 3;
  62856. }
  62857. if (instance._closePath) {
  62858. positions[i] = path[0].x;
  62859. positions[i + 1] = path[0].y;
  62860. positions[i + 2] = path[0].z;
  62861. i += 3;
  62862. }
  62863. }
  62864. }
  62865. };
  62866. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62867. positionFunction(positions);
  62868. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  62869. instance._boundingInfo.update(instance._worldMatrix);
  62870. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62871. if (options.colors) {
  62872. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62873. for (var c = 0; c < options.colors.length; c++) {
  62874. colors[c * 4] = options.colors[c].r;
  62875. colors[c * 4 + 1] = options.colors[c].g;
  62876. colors[c * 4 + 2] = options.colors[c].b;
  62877. colors[c * 4 + 3] = options.colors[c].a;
  62878. }
  62879. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  62880. }
  62881. if (options.uvs) {
  62882. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62883. for (var i = 0; i < options.uvs.length; i++) {
  62884. uvs[i * 2] = options.uvs[i].x;
  62885. uvs[i * 2 + 1] = options.uvs[i].y;
  62886. }
  62887. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  62888. }
  62889. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  62890. var indices = instance.getIndices();
  62891. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62892. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  62893. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  62894. if (instance._closePath) {
  62895. var indexFirst = 0;
  62896. var indexLast = 0;
  62897. for (var p = 0; p < pathArray.length; p++) {
  62898. indexFirst = instance._idx[p] * 3;
  62899. if (p + 1 < pathArray.length) {
  62900. indexLast = (instance._idx[p + 1] - 1) * 3;
  62901. }
  62902. else {
  62903. indexLast = normals.length - 3;
  62904. }
  62905. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  62906. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  62907. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  62908. normals[indexLast] = normals[indexFirst];
  62909. normals[indexLast + 1] = normals[indexFirst + 1];
  62910. normals[indexLast + 2] = normals[indexFirst + 2];
  62911. }
  62912. }
  62913. if (!(instance.areNormalsFrozen)) {
  62914. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  62915. }
  62916. }
  62917. return instance;
  62918. }
  62919. else { // new ribbon creation
  62920. var ribbon = new BABYLON.Mesh(name, scene);
  62921. ribbon._originalBuilderSideOrientation = sideOrientation;
  62922. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  62923. if (closePath) {
  62924. ribbon._idx = vertexData._idx;
  62925. }
  62926. ribbon._closePath = closePath;
  62927. ribbon._closeArray = closeArray;
  62928. vertexData.applyToMesh(ribbon, updatable);
  62929. return ribbon;
  62930. }
  62931. };
  62932. /**
  62933. * Creates a cylinder or a cone mesh
  62934. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  62935. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  62936. * * 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.
  62937. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  62938. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  62939. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  62940. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  62941. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  62942. * * 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).
  62943. * * 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
  62944. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  62945. * * 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
  62946. * * 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.
  62947. * * If `enclose` is false, a ring surface is one element.
  62948. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  62949. * * 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
  62950. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62951. * * 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
  62952. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62953. * @param name defines the name of the mesh
  62954. * @param options defines the options used to create the mesh
  62955. * @param scene defines the hosting scene
  62956. * @returns the cylinder mesh
  62957. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  62958. */
  62959. MeshBuilder.CreateCylinder = function (name, options, scene) {
  62960. var cylinder = new BABYLON.Mesh(name, scene);
  62961. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62962. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  62963. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  62964. vertexData.applyToMesh(cylinder, options.updatable);
  62965. return cylinder;
  62966. };
  62967. /**
  62968. * Creates a torus mesh
  62969. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  62970. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  62971. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  62972. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62973. * * 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
  62974. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62975. * @param name defines the name of the mesh
  62976. * @param options defines the options used to create the mesh
  62977. * @param scene defines the hosting scene
  62978. * @returns the torus mesh
  62979. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  62980. */
  62981. MeshBuilder.CreateTorus = function (name, options, scene) {
  62982. var torus = new BABYLON.Mesh(name, scene);
  62983. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62984. torus._originalBuilderSideOrientation = options.sideOrientation;
  62985. var vertexData = BABYLON.VertexData.CreateTorus(options);
  62986. vertexData.applyToMesh(torus, options.updatable);
  62987. return torus;
  62988. };
  62989. /**
  62990. * Creates a torus knot mesh
  62991. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  62992. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  62993. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  62994. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  62995. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62996. * * 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
  62997. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62998. * @param name defines the name of the mesh
  62999. * @param options defines the options used to create the mesh
  63000. * @param scene defines the hosting scene
  63001. * @returns the torus knot mesh
  63002. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  63003. */
  63004. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  63005. var torusKnot = new BABYLON.Mesh(name, scene);
  63006. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63007. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  63008. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  63009. vertexData.applyToMesh(torusKnot, options.updatable);
  63010. return torusKnot;
  63011. };
  63012. /**
  63013. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  63014. * * 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
  63015. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  63016. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  63017. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  63018. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  63019. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  63020. * * 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
  63021. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  63022. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63023. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  63024. * @param name defines the name of the new line system
  63025. * @param options defines the options used to create the line system
  63026. * @param scene defines the hosting scene
  63027. * @returns a new line system mesh
  63028. */
  63029. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  63030. var instance = options.instance;
  63031. var lines = options.lines;
  63032. var colors = options.colors;
  63033. if (instance) { // lines update
  63034. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63035. var vertexColor;
  63036. var lineColors;
  63037. if (colors) {
  63038. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63039. }
  63040. var i = 0;
  63041. var c = 0;
  63042. for (var l = 0; l < lines.length; l++) {
  63043. var points = lines[l];
  63044. for (var p = 0; p < points.length; p++) {
  63045. positions[i] = points[p].x;
  63046. positions[i + 1] = points[p].y;
  63047. positions[i + 2] = points[p].z;
  63048. if (colors && vertexColor) {
  63049. lineColors = colors[l];
  63050. vertexColor[c] = lineColors[p].r;
  63051. vertexColor[c + 1] = lineColors[p].g;
  63052. vertexColor[c + 2] = lineColors[p].b;
  63053. vertexColor[c + 3] = lineColors[p].a;
  63054. c += 4;
  63055. }
  63056. i += 3;
  63057. }
  63058. }
  63059. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63060. if (colors && vertexColor) {
  63061. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  63062. }
  63063. return instance;
  63064. }
  63065. // line system creation
  63066. var useVertexColor = (colors) ? true : false;
  63067. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  63068. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  63069. vertexData.applyToMesh(lineSystem, options.updatable);
  63070. return lineSystem;
  63071. };
  63072. /**
  63073. * Creates a line mesh
  63074. * 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
  63075. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63076. * * The parameter `points` is an array successive Vector3
  63077. * * 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
  63078. * * The optional parameter `colors` is an array of successive Color4, one per line point
  63079. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  63080. * * When updating an instance, remember that only point positions can change, not the number of points
  63081. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63082. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  63083. * @param name defines the name of the new line system
  63084. * @param options defines the options used to create the line system
  63085. * @param scene defines the hosting scene
  63086. * @returns a new line mesh
  63087. */
  63088. MeshBuilder.CreateLines = function (name, options, scene) {
  63089. if (scene === void 0) { scene = null; }
  63090. var colors = (options.colors) ? [options.colors] : null;
  63091. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  63092. return lines;
  63093. };
  63094. /**
  63095. * Creates a dashed line mesh
  63096. * * 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
  63097. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63098. * * The parameter `points` is an array successive Vector3
  63099. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  63100. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  63101. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  63102. * * 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
  63103. * * When updating an instance, remember that only point positions can change, not the number of points
  63104. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63105. * @param name defines the name of the mesh
  63106. * @param options defines the options used to create the mesh
  63107. * @param scene defines the hosting scene
  63108. * @returns the dashed line mesh
  63109. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  63110. */
  63111. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  63112. if (scene === void 0) { scene = null; }
  63113. var points = options.points;
  63114. var instance = options.instance;
  63115. var gapSize = options.gapSize || 1;
  63116. var dashSize = options.dashSize || 3;
  63117. if (instance) { // dashed lines update
  63118. var positionFunction = function (positions) {
  63119. var curvect = BABYLON.Vector3.Zero();
  63120. var nbSeg = positions.length / 6;
  63121. var lg = 0;
  63122. var nb = 0;
  63123. var shft = 0;
  63124. var dashshft = 0;
  63125. var curshft = 0;
  63126. var p = 0;
  63127. var i = 0;
  63128. var j = 0;
  63129. for (i = 0; i < points.length - 1; i++) {
  63130. points[i + 1].subtractToRef(points[i], curvect);
  63131. lg += curvect.length();
  63132. }
  63133. shft = lg / nbSeg;
  63134. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  63135. for (i = 0; i < points.length - 1; i++) {
  63136. points[i + 1].subtractToRef(points[i], curvect);
  63137. nb = Math.floor(curvect.length() / shft);
  63138. curvect.normalize();
  63139. j = 0;
  63140. while (j < nb && p < positions.length) {
  63141. curshft = shft * j;
  63142. positions[p] = points[i].x + curshft * curvect.x;
  63143. positions[p + 1] = points[i].y + curshft * curvect.y;
  63144. positions[p + 2] = points[i].z + curshft * curvect.z;
  63145. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  63146. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  63147. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  63148. p += 6;
  63149. j++;
  63150. }
  63151. }
  63152. while (p < positions.length) {
  63153. positions[p] = points[i].x;
  63154. positions[p + 1] = points[i].y;
  63155. positions[p + 2] = points[i].z;
  63156. p += 3;
  63157. }
  63158. };
  63159. instance.updateMeshPositions(positionFunction, false);
  63160. return instance;
  63161. }
  63162. // dashed lines creation
  63163. var dashedLines = new BABYLON.LinesMesh(name, scene);
  63164. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  63165. vertexData.applyToMesh(dashedLines, options.updatable);
  63166. dashedLines.dashSize = dashSize;
  63167. dashedLines.gapSize = gapSize;
  63168. return dashedLines;
  63169. };
  63170. /**
  63171. * 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.
  63172. * * 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.
  63173. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63174. * * 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.
  63175. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  63176. * * 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
  63177. * * 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
  63178. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  63179. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63180. * * 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
  63181. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  63182. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63183. * @param name defines the name of the mesh
  63184. * @param options defines the options used to create the mesh
  63185. * @param scene defines the hosting scene
  63186. * @returns the extruded shape mesh
  63187. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63188. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63189. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63190. */
  63191. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  63192. if (scene === void 0) { scene = null; }
  63193. var path = options.path;
  63194. var shape = options.shape;
  63195. var scale = options.scale || 1;
  63196. var rotation = options.rotation || 0;
  63197. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63198. var updatable = options.updatable;
  63199. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63200. var instance = options.instance || null;
  63201. var invertUV = options.invertUV || false;
  63202. 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);
  63203. };
  63204. /**
  63205. * Creates an custom extruded shape mesh.
  63206. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  63207. * * 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.
  63208. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63209. * * 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
  63210. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  63211. * * 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
  63212. * * It must returns a float value that will be the scale value applied to the shape on each path point
  63213. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  63214. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  63215. * * 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
  63216. * * 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
  63217. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  63218. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63219. * * 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
  63220. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63221. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63222. * @param name defines the name of the mesh
  63223. * @param options defines the options used to create the mesh
  63224. * @param scene defines the hosting scene
  63225. * @returns the custom extruded shape mesh
  63226. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  63227. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63228. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63229. */
  63230. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  63231. var path = options.path;
  63232. var shape = options.shape;
  63233. var scaleFunction = options.scaleFunction || (function () { return 1; });
  63234. var rotationFunction = options.rotationFunction || (function () { return 0; });
  63235. var ribbonCloseArray = options.ribbonCloseArray || false;
  63236. var ribbonClosePath = options.ribbonClosePath || false;
  63237. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63238. var updatable = options.updatable;
  63239. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63240. var instance = options.instance;
  63241. var invertUV = options.invertUV || false;
  63242. 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);
  63243. };
  63244. /**
  63245. * Creates lathe mesh.
  63246. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  63247. * * 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
  63248. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  63249. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  63250. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  63251. * * 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
  63252. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  63253. * * 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
  63254. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63255. * * 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
  63256. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63257. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63258. * @param name defines the name of the mesh
  63259. * @param options defines the options used to create the mesh
  63260. * @param scene defines the hosting scene
  63261. * @returns the lathe mesh
  63262. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  63263. */
  63264. MeshBuilder.CreateLathe = function (name, options, scene) {
  63265. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  63266. var closed = (options.closed === undefined) ? true : options.closed;
  63267. var shape = options.shape;
  63268. var radius = options.radius || 1;
  63269. var tessellation = options.tessellation || 64;
  63270. var clip = options.clip || 0;
  63271. var updatable = options.updatable;
  63272. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63273. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63274. var pi2 = Math.PI * 2;
  63275. var paths = new Array();
  63276. var invertUV = options.invertUV || false;
  63277. var i = 0;
  63278. var p = 0;
  63279. var step = pi2 / tessellation * arc;
  63280. var rotated;
  63281. var path = new Array();
  63282. for (i = 0; i <= tessellation - clip; i++) {
  63283. var path = [];
  63284. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  63285. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  63286. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  63287. }
  63288. for (p = 0; p < shape.length; p++) {
  63289. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  63290. path.push(rotated);
  63291. }
  63292. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  63293. 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));
  63294. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  63295. }
  63296. paths.push(path);
  63297. }
  63298. // lathe ribbon
  63299. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63300. return lathe;
  63301. };
  63302. /**
  63303. * Creates a plane mesh
  63304. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  63305. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  63306. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  63307. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63308. * * 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
  63309. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63310. * @param name defines the name of the mesh
  63311. * @param options defines the options used to create the mesh
  63312. * @param scene defines the hosting scene
  63313. * @returns the plane mesh
  63314. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63315. */
  63316. MeshBuilder.CreatePlane = function (name, options, scene) {
  63317. var plane = new BABYLON.Mesh(name, scene);
  63318. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63319. plane._originalBuilderSideOrientation = options.sideOrientation;
  63320. var vertexData = BABYLON.VertexData.CreatePlane(options);
  63321. vertexData.applyToMesh(plane, options.updatable);
  63322. if (options.sourcePlane) {
  63323. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  63324. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  63325. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  63326. plane.rotate(vectorProduct, product);
  63327. }
  63328. return plane;
  63329. };
  63330. /**
  63331. * Creates a ground mesh
  63332. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  63333. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  63334. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63335. * @param name defines the name of the mesh
  63336. * @param options defines the options used to create the mesh
  63337. * @param scene defines the hosting scene
  63338. * @returns the ground mesh
  63339. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63340. */
  63341. MeshBuilder.CreateGround = function (name, options, scene) {
  63342. var ground = new BABYLON.GroundMesh(name, scene);
  63343. ground._setReady(false);
  63344. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  63345. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  63346. ground._width = options.width || 1;
  63347. ground._height = options.height || 1;
  63348. ground._maxX = ground._width / 2;
  63349. ground._maxZ = ground._height / 2;
  63350. ground._minX = -ground._maxX;
  63351. ground._minZ = -ground._maxZ;
  63352. var vertexData = BABYLON.VertexData.CreateGround(options);
  63353. vertexData.applyToMesh(ground, options.updatable);
  63354. ground._setReady(true);
  63355. return ground;
  63356. };
  63357. /**
  63358. * Creates a tiled ground mesh
  63359. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  63360. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  63361. * * 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
  63362. * * 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
  63363. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63364. * @param name defines the name of the mesh
  63365. * @param options defines the options used to create the mesh
  63366. * @param scene defines the hosting scene
  63367. * @returns the tiled ground mesh
  63368. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  63369. */
  63370. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  63371. var tiledGround = new BABYLON.Mesh(name, scene);
  63372. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  63373. vertexData.applyToMesh(tiledGround, options.updatable);
  63374. return tiledGround;
  63375. };
  63376. /**
  63377. * Creates a ground mesh from a height map
  63378. * * The parameter `url` sets the URL of the height map image resource.
  63379. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  63380. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  63381. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  63382. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  63383. * * 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.
  63384. * * 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).
  63385. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63386. * @param name defines the name of the mesh
  63387. * @param url defines the url to the height map
  63388. * @param options defines the options used to create the mesh
  63389. * @param scene defines the hosting scene
  63390. * @returns the ground mesh
  63391. * @see http://doc.babylonjs.com/babylon101/height_map
  63392. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  63393. */
  63394. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  63395. var width = options.width || 10.0;
  63396. var height = options.height || 10.0;
  63397. var subdivisions = options.subdivisions || 1 | 0;
  63398. var minHeight = options.minHeight || 0.0;
  63399. var maxHeight = options.maxHeight || 1.0;
  63400. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  63401. var updatable = options.updatable;
  63402. var onReady = options.onReady;
  63403. var ground = new BABYLON.GroundMesh(name, scene);
  63404. ground._subdivisionsX = subdivisions;
  63405. ground._subdivisionsY = subdivisions;
  63406. ground._width = width;
  63407. ground._height = height;
  63408. ground._maxX = ground._width / 2.0;
  63409. ground._maxZ = ground._height / 2.0;
  63410. ground._minX = -ground._maxX;
  63411. ground._minZ = -ground._maxZ;
  63412. ground._setReady(false);
  63413. var onload = function (img) {
  63414. // Getting height map data
  63415. var canvas = document.createElement("canvas");
  63416. var context = canvas.getContext("2d");
  63417. if (!context) {
  63418. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  63419. }
  63420. if (scene.isDisposed) {
  63421. return;
  63422. }
  63423. var bufferWidth = img.width;
  63424. var bufferHeight = img.height;
  63425. canvas.width = bufferWidth;
  63426. canvas.height = bufferHeight;
  63427. context.drawImage(img, 0, 0);
  63428. // Create VertexData from map data
  63429. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  63430. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  63431. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  63432. width: width, height: height,
  63433. subdivisions: subdivisions,
  63434. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  63435. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  63436. });
  63437. vertexData.applyToMesh(ground, updatable);
  63438. //execute ready callback, if set
  63439. if (onReady) {
  63440. onReady(ground);
  63441. }
  63442. ground._setReady(true);
  63443. };
  63444. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  63445. return ground;
  63446. };
  63447. /**
  63448. * Creates a polygon mesh
  63449. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  63450. * * 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
  63451. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63452. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63453. * * 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)
  63454. * * Remember you can only change the shape positions, not their number when updating a polygon
  63455. * @param name defines the name of the mesh
  63456. * @param options defines the options used to create the mesh
  63457. * @param scene defines the hosting scene
  63458. * @returns the polygon mesh
  63459. */
  63460. MeshBuilder.CreatePolygon = function (name, options, scene) {
  63461. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63462. var shape = options.shape;
  63463. var holes = options.holes || [];
  63464. var depth = options.depth || 0;
  63465. var contours = [];
  63466. var hole = [];
  63467. for (var i = 0; i < shape.length; i++) {
  63468. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  63469. }
  63470. var epsilon = 0.00000001;
  63471. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  63472. contours.pop();
  63473. }
  63474. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  63475. for (var hNb = 0; hNb < holes.length; hNb++) {
  63476. hole = [];
  63477. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  63478. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  63479. }
  63480. polygonTriangulation.addHole(hole);
  63481. }
  63482. var polygon = polygonTriangulation.build(options.updatable, depth);
  63483. polygon._originalBuilderSideOrientation = options.sideOrientation;
  63484. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  63485. vertexData.applyToMesh(polygon, options.updatable);
  63486. return polygon;
  63487. };
  63488. ;
  63489. /**
  63490. * Creates an extruded polygon mesh, with depth in the Y direction.
  63491. * * 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)
  63492. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63493. * @param name defines the name of the mesh
  63494. * @param options defines the options used to create the mesh
  63495. * @param scene defines the hosting scene
  63496. * @returns the polygon mesh
  63497. */
  63498. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  63499. return MeshBuilder.CreatePolygon(name, options, scene);
  63500. };
  63501. ;
  63502. /**
  63503. * Creates a tube mesh.
  63504. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63505. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  63506. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  63507. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  63508. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  63509. * * 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)
  63510. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  63511. * * 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
  63512. * * 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
  63513. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63514. * * 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
  63515. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63516. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63517. * @param name defines the name of the mesh
  63518. * @param options defines the options used to create the mesh
  63519. * @param scene defines the hosting scene
  63520. * @returns the tube mesh
  63521. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63522. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  63523. */
  63524. MeshBuilder.CreateTube = function (name, options, scene) {
  63525. var path = options.path;
  63526. var instance = options.instance;
  63527. var radius = 1.0;
  63528. if (instance) {
  63529. radius = instance.radius;
  63530. }
  63531. if (options.radius !== undefined) {
  63532. radius = options.radius;
  63533. }
  63534. ;
  63535. var tessellation = options.tessellation || 64 | 0;
  63536. var radiusFunction = options.radiusFunction || null;
  63537. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63538. var invertUV = options.invertUV || false;
  63539. var updatable = options.updatable;
  63540. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63541. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  63542. // tube geometry
  63543. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  63544. var tangents = path3D.getTangents();
  63545. var normals = path3D.getNormals();
  63546. var distances = path3D.getDistances();
  63547. var pi2 = Math.PI * 2;
  63548. var step = pi2 / tessellation * arc;
  63549. var returnRadius = function () { return radius; };
  63550. var radiusFunctionFinal = radiusFunction || returnRadius;
  63551. var circlePath;
  63552. var rad;
  63553. var normal;
  63554. var rotated;
  63555. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63556. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63557. for (var i = 0; i < path.length; i++) {
  63558. rad = radiusFunctionFinal(i, distances[i]); // current radius
  63559. circlePath = Array(); // current circle array
  63560. normal = normals[i]; // current normal
  63561. for (var t = 0; t < tessellation; t++) {
  63562. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  63563. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  63564. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  63565. rotated.scaleInPlace(rad).addInPlace(path[i]);
  63566. circlePath[t] = rotated;
  63567. }
  63568. circlePaths[index] = circlePath;
  63569. index++;
  63570. }
  63571. // cap
  63572. var capPath = function (nbPoints, pathIndex) {
  63573. var pointCap = Array();
  63574. for (var i = 0; i < nbPoints; i++) {
  63575. pointCap.push(path[pathIndex]);
  63576. }
  63577. return pointCap;
  63578. };
  63579. switch (cap) {
  63580. case BABYLON.Mesh.NO_CAP:
  63581. break;
  63582. case BABYLON.Mesh.CAP_START:
  63583. circlePaths[0] = capPath(tessellation, 0);
  63584. circlePaths[1] = circlePaths[2].slice(0);
  63585. break;
  63586. case BABYLON.Mesh.CAP_END:
  63587. circlePaths[index] = circlePaths[index - 1].slice(0);
  63588. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63589. break;
  63590. case BABYLON.Mesh.CAP_ALL:
  63591. circlePaths[0] = capPath(tessellation, 0);
  63592. circlePaths[1] = circlePaths[2].slice(0);
  63593. circlePaths[index] = circlePaths[index - 1].slice(0);
  63594. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63595. break;
  63596. default:
  63597. break;
  63598. }
  63599. return circlePaths;
  63600. };
  63601. var path3D;
  63602. var pathArray;
  63603. if (instance) { // tube update
  63604. var arc = options.arc || instance.arc;
  63605. path3D = (instance.path3D).update(path);
  63606. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  63607. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  63608. instance.path3D = path3D;
  63609. instance.pathArray = pathArray;
  63610. instance.arc = arc;
  63611. instance.radius = radius;
  63612. return instance;
  63613. }
  63614. // tube creation
  63615. path3D = new BABYLON.Path3D(path);
  63616. var newPathArray = new Array();
  63617. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63618. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  63619. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63620. tube.pathArray = pathArray;
  63621. tube.path3D = path3D;
  63622. tube.tessellation = tessellation;
  63623. tube.cap = cap;
  63624. tube.arc = options.arc;
  63625. tube.radius = radius;
  63626. return tube;
  63627. };
  63628. /**
  63629. * Creates a polyhedron mesh
  63630. * * 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
  63631. * * The parameter `size` (positive float, default 1) sets the polygon size
  63632. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  63633. * * 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`
  63634. * * 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
  63635. * * 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)`)
  63636. * * 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
  63637. * * 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
  63638. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63639. * * 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
  63640. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63641. * @param name defines the name of the mesh
  63642. * @param options defines the options used to create the mesh
  63643. * @param scene defines the hosting scene
  63644. * @returns the polyhedron mesh
  63645. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  63646. */
  63647. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  63648. var polyhedron = new BABYLON.Mesh(name, scene);
  63649. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63650. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  63651. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  63652. vertexData.applyToMesh(polyhedron, options.updatable);
  63653. return polyhedron;
  63654. };
  63655. /**
  63656. * Creates a decal mesh.
  63657. * 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
  63658. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  63659. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  63660. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  63661. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  63662. * @param name defines the name of the mesh
  63663. * @param sourceMesh defines the mesh where the decal must be applied
  63664. * @param options defines the options used to create the mesh
  63665. * @param scene defines the hosting scene
  63666. * @returns the decal mesh
  63667. * @see http://doc.babylonjs.com/how_to/decals
  63668. */
  63669. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  63670. var indices = sourceMesh.getIndices();
  63671. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63672. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63673. var position = options.position || BABYLON.Vector3.Zero();
  63674. var normal = options.normal || BABYLON.Vector3.Up();
  63675. var size = options.size || BABYLON.Vector3.One();
  63676. var angle = options.angle || 0;
  63677. // Getting correct rotation
  63678. if (!normal) {
  63679. var target = new BABYLON.Vector3(0, 0, 1);
  63680. var camera = sourceMesh.getScene().activeCamera;
  63681. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  63682. normal = camera.globalPosition.subtract(cameraWorldTarget);
  63683. }
  63684. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63685. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63686. var pitch = Math.atan2(normal.y, len);
  63687. // Matrix
  63688. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63689. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63690. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63691. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  63692. var vertexData = new BABYLON.VertexData();
  63693. vertexData.indices = [];
  63694. vertexData.positions = [];
  63695. vertexData.normals = [];
  63696. vertexData.uvs = [];
  63697. var currentVertexDataIndex = 0;
  63698. var extractDecalVector3 = function (indexId) {
  63699. var result = new BABYLON.PositionNormalVertex();
  63700. if (!indices || !positions || !normals) {
  63701. return result;
  63702. }
  63703. var vertexId = indices[indexId];
  63704. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  63705. // Send vector to decal local world
  63706. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  63707. // Get normal
  63708. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  63709. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  63710. return result;
  63711. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  63712. var clip = function (vertices, axis) {
  63713. if (vertices.length === 0) {
  63714. return vertices;
  63715. }
  63716. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  63717. var clipVertices = function (v0, v1) {
  63718. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  63719. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  63720. };
  63721. var result = new Array();
  63722. for (var index = 0; index < vertices.length; index += 3) {
  63723. var v1Out;
  63724. var v2Out;
  63725. var v3Out;
  63726. var total = 0;
  63727. var nV1 = null;
  63728. var nV2 = null;
  63729. var nV3 = null;
  63730. var nV4 = null;
  63731. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  63732. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  63733. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  63734. v1Out = d1 > 0;
  63735. v2Out = d2 > 0;
  63736. v3Out = d3 > 0;
  63737. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  63738. switch (total) {
  63739. case 0:
  63740. result.push(vertices[index]);
  63741. result.push(vertices[index + 1]);
  63742. result.push(vertices[index + 2]);
  63743. break;
  63744. case 1:
  63745. if (v1Out) {
  63746. nV1 = vertices[index + 1];
  63747. nV2 = vertices[index + 2];
  63748. nV3 = clipVertices(vertices[index], nV1);
  63749. nV4 = clipVertices(vertices[index], nV2);
  63750. }
  63751. if (v2Out) {
  63752. nV1 = vertices[index];
  63753. nV2 = vertices[index + 2];
  63754. nV3 = clipVertices(vertices[index + 1], nV1);
  63755. nV4 = clipVertices(vertices[index + 1], nV2);
  63756. result.push(nV3);
  63757. result.push(nV2.clone());
  63758. result.push(nV1.clone());
  63759. result.push(nV2.clone());
  63760. result.push(nV3.clone());
  63761. result.push(nV4);
  63762. break;
  63763. }
  63764. if (v3Out) {
  63765. nV1 = vertices[index];
  63766. nV2 = vertices[index + 1];
  63767. nV3 = clipVertices(vertices[index + 2], nV1);
  63768. nV4 = clipVertices(vertices[index + 2], nV2);
  63769. }
  63770. if (nV1 && nV2 && nV3 && nV4) {
  63771. result.push(nV1.clone());
  63772. result.push(nV2.clone());
  63773. result.push(nV3);
  63774. result.push(nV4);
  63775. result.push(nV3.clone());
  63776. result.push(nV2.clone());
  63777. }
  63778. break;
  63779. case 2:
  63780. if (!v1Out) {
  63781. nV1 = vertices[index].clone();
  63782. nV2 = clipVertices(nV1, vertices[index + 1]);
  63783. nV3 = clipVertices(nV1, vertices[index + 2]);
  63784. result.push(nV1);
  63785. result.push(nV2);
  63786. result.push(nV3);
  63787. }
  63788. if (!v2Out) {
  63789. nV1 = vertices[index + 1].clone();
  63790. nV2 = clipVertices(nV1, vertices[index + 2]);
  63791. nV3 = clipVertices(nV1, vertices[index]);
  63792. result.push(nV1);
  63793. result.push(nV2);
  63794. result.push(nV3);
  63795. }
  63796. if (!v3Out) {
  63797. nV1 = vertices[index + 2].clone();
  63798. nV2 = clipVertices(nV1, vertices[index]);
  63799. nV3 = clipVertices(nV1, vertices[index + 1]);
  63800. result.push(nV1);
  63801. result.push(nV2);
  63802. result.push(nV3);
  63803. }
  63804. break;
  63805. case 3:
  63806. break;
  63807. }
  63808. }
  63809. return result;
  63810. };
  63811. for (var index = 0; index < indices.length; index += 3) {
  63812. var faceVertices = new Array();
  63813. faceVertices.push(extractDecalVector3(index));
  63814. faceVertices.push(extractDecalVector3(index + 1));
  63815. faceVertices.push(extractDecalVector3(index + 2));
  63816. // Clip
  63817. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  63818. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  63819. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  63820. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  63821. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  63822. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  63823. if (faceVertices.length === 0) {
  63824. continue;
  63825. }
  63826. // Add UVs and get back to world
  63827. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  63828. var vertex = faceVertices[vIndex];
  63829. //TODO check for Int32Array | Uint32Array | Uint16Array
  63830. vertexData.indices.push(currentVertexDataIndex);
  63831. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  63832. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  63833. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  63834. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  63835. currentVertexDataIndex++;
  63836. }
  63837. }
  63838. // Return mesh
  63839. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  63840. vertexData.applyToMesh(decal);
  63841. decal.position = position.clone();
  63842. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  63843. return decal;
  63844. };
  63845. // Privates
  63846. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  63847. // extrusion geometry
  63848. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  63849. var tangents = path3D.getTangents();
  63850. var normals = path3D.getNormals();
  63851. var binormals = path3D.getBinormals();
  63852. var distances = path3D.getDistances();
  63853. var angle = 0;
  63854. var returnScale = function () { return scale !== null ? scale : 1; };
  63855. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  63856. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  63857. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  63858. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63859. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63860. for (var i = 0; i < curve.length; i++) {
  63861. var shapePath = new Array();
  63862. var angleStep = rotate(i, distances[i]);
  63863. var scaleRatio = scl(i, distances[i]);
  63864. for (var p = 0; p < shape.length; p++) {
  63865. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  63866. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  63867. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  63868. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  63869. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  63870. shapePath[p] = rotated;
  63871. }
  63872. shapePaths[index] = shapePath;
  63873. angle += angleStep;
  63874. index++;
  63875. }
  63876. // cap
  63877. var capPath = function (shapePath) {
  63878. var pointCap = Array();
  63879. var barycenter = BABYLON.Vector3.Zero();
  63880. var i;
  63881. for (i = 0; i < shapePath.length; i++) {
  63882. barycenter.addInPlace(shapePath[i]);
  63883. }
  63884. barycenter.scaleInPlace(1.0 / shapePath.length);
  63885. for (i = 0; i < shapePath.length; i++) {
  63886. pointCap.push(barycenter);
  63887. }
  63888. return pointCap;
  63889. };
  63890. switch (cap) {
  63891. case BABYLON.Mesh.NO_CAP:
  63892. break;
  63893. case BABYLON.Mesh.CAP_START:
  63894. shapePaths[0] = capPath(shapePaths[2]);
  63895. shapePaths[1] = shapePaths[2];
  63896. break;
  63897. case BABYLON.Mesh.CAP_END:
  63898. shapePaths[index] = shapePaths[index - 1];
  63899. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63900. break;
  63901. case BABYLON.Mesh.CAP_ALL:
  63902. shapePaths[0] = capPath(shapePaths[2]);
  63903. shapePaths[1] = shapePaths[2];
  63904. shapePaths[index] = shapePaths[index - 1];
  63905. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63906. break;
  63907. default:
  63908. break;
  63909. }
  63910. return shapePaths;
  63911. };
  63912. var path3D;
  63913. var pathArray;
  63914. if (instance) { // instance update
  63915. path3D = (instance.path3D).update(curve);
  63916. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  63917. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  63918. return instance;
  63919. }
  63920. // extruded shape creation
  63921. path3D = new BABYLON.Path3D(curve);
  63922. var newShapePaths = new Array();
  63923. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63924. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  63925. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  63926. extrudedGeneric.pathArray = pathArray;
  63927. extrudedGeneric.path3D = path3D;
  63928. extrudedGeneric.cap = cap;
  63929. return extrudedGeneric;
  63930. };
  63931. return MeshBuilder;
  63932. }());
  63933. BABYLON.MeshBuilder = MeshBuilder;
  63934. })(BABYLON || (BABYLON = {}));
  63935. //# sourceMappingURL=babylon.meshBuilder.js.map
  63936. var BABYLON;
  63937. (function (BABYLON) {
  63938. /**
  63939. * Draco compression (https://google.github.io/draco/)
  63940. *
  63941. * This class wraps the Draco module.
  63942. *
  63943. * **Encoder**
  63944. *
  63945. * The encoder is not currently implemented.
  63946. *
  63947. * **Decoder**
  63948. *
  63949. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  63950. *
  63951. * To update the configuration, use the following code:
  63952. * ```javascript
  63953. * BABYLON.DracoCompression.Configuration = {
  63954. * decoder: {
  63955. * wasmUrl: "<url to the WebAssembly library>",
  63956. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  63957. * fallbackUrl: "<url to the fallback JavaScript library>",
  63958. * }
  63959. * };
  63960. * ```
  63961. *
  63962. * 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.
  63963. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  63964. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  63965. *
  63966. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  63967. * ```javascript
  63968. * var dracoCompression = new BABYLON.DracoCompression();
  63969. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  63970. * [BABYLON.VertexBuffer.PositionKind]: 0
  63971. * });
  63972. * ```
  63973. *
  63974. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  63975. */
  63976. var DracoCompression = /** @class */ (function () {
  63977. /**
  63978. * Constructor
  63979. */
  63980. function DracoCompression() {
  63981. }
  63982. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  63983. /**
  63984. * Returns true if the decoder is available.
  63985. */
  63986. get: function () {
  63987. if (typeof DracoDecoderModule !== "undefined") {
  63988. return true;
  63989. }
  63990. var decoder = DracoCompression.Configuration.decoder;
  63991. if (decoder) {
  63992. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63993. return true;
  63994. }
  63995. if (decoder.fallbackUrl) {
  63996. return true;
  63997. }
  63998. }
  63999. return false;
  64000. },
  64001. enumerable: true,
  64002. configurable: true
  64003. });
  64004. /**
  64005. * Stop all async operations and release resources.
  64006. */
  64007. DracoCompression.prototype.dispose = function () {
  64008. };
  64009. /**
  64010. * Decode Draco compressed mesh data to vertex data.
  64011. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  64012. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  64013. * @returns A promise that resolves with the decoded vertex data
  64014. */
  64015. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  64016. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  64017. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  64018. var module = wrappedModule.module;
  64019. var vertexData = new BABYLON.VertexData();
  64020. var buffer = new module.DecoderBuffer();
  64021. buffer.Init(dataView, dataView.byteLength);
  64022. var decoder = new module.Decoder();
  64023. var geometry;
  64024. var status;
  64025. try {
  64026. var type = decoder.GetEncodedGeometryType(buffer);
  64027. switch (type) {
  64028. case module.TRIANGULAR_MESH:
  64029. geometry = new module.Mesh();
  64030. status = decoder.DecodeBufferToMesh(buffer, geometry);
  64031. break;
  64032. case module.POINT_CLOUD:
  64033. geometry = new module.PointCloud();
  64034. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  64035. break;
  64036. default:
  64037. throw new Error("Invalid geometry type " + type);
  64038. }
  64039. if (!status.ok() || !geometry.ptr) {
  64040. throw new Error(status.error_msg());
  64041. }
  64042. var numPoints = geometry.num_points();
  64043. if (type === module.TRIANGULAR_MESH) {
  64044. var numFaces = geometry.num_faces();
  64045. var faceIndices = new module.DracoInt32Array();
  64046. try {
  64047. var indices = new Uint32Array(numFaces * 3);
  64048. for (var i = 0; i < numFaces; i++) {
  64049. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  64050. var offset = i * 3;
  64051. indices[offset + 0] = faceIndices.GetValue(0);
  64052. indices[offset + 1] = faceIndices.GetValue(1);
  64053. indices[offset + 2] = faceIndices.GetValue(2);
  64054. }
  64055. vertexData.indices = indices;
  64056. }
  64057. finally {
  64058. module.destroy(faceIndices);
  64059. }
  64060. }
  64061. for (var kind in attributes) {
  64062. var uniqueId = attributes[kind];
  64063. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  64064. var dracoData = new module.DracoFloat32Array();
  64065. try {
  64066. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  64067. var babylonData = new Float32Array(numPoints * attribute.num_components());
  64068. for (var i = 0; i < babylonData.length; i++) {
  64069. babylonData[i] = dracoData.GetValue(i);
  64070. }
  64071. vertexData.set(babylonData, kind);
  64072. }
  64073. finally {
  64074. module.destroy(dracoData);
  64075. }
  64076. }
  64077. }
  64078. finally {
  64079. if (geometry) {
  64080. module.destroy(geometry);
  64081. }
  64082. module.destroy(decoder);
  64083. module.destroy(buffer);
  64084. }
  64085. return vertexData;
  64086. });
  64087. };
  64088. DracoCompression._GetDecoderModule = function () {
  64089. if (!DracoCompression._DecoderModulePromise) {
  64090. var promise = null;
  64091. var config_1 = {};
  64092. if (typeof DracoDecoderModule !== "undefined") {
  64093. promise = Promise.resolve();
  64094. }
  64095. else {
  64096. var decoder = DracoCompression.Configuration.decoder;
  64097. if (decoder) {
  64098. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64099. promise = Promise.all([
  64100. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  64101. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  64102. config_1.wasmBinary = data;
  64103. })
  64104. ]);
  64105. }
  64106. else if (decoder.fallbackUrl) {
  64107. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  64108. }
  64109. }
  64110. }
  64111. if (!promise) {
  64112. throw new Error("Draco decoder module is not available");
  64113. }
  64114. DracoCompression._DecoderModulePromise = promise.then(function () {
  64115. return new Promise(function (resolve) {
  64116. config_1.onModuleLoaded = function (decoderModule) {
  64117. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  64118. resolve({ module: decoderModule });
  64119. };
  64120. DracoDecoderModule(config_1);
  64121. });
  64122. });
  64123. }
  64124. return DracoCompression._DecoderModulePromise;
  64125. };
  64126. DracoCompression._LoadScriptAsync = function (url) {
  64127. return new Promise(function (resolve, reject) {
  64128. BABYLON.Tools.LoadScript(url, function () {
  64129. resolve();
  64130. }, function (message) {
  64131. reject(new Error(message));
  64132. });
  64133. });
  64134. };
  64135. DracoCompression._LoadFileAsync = function (url) {
  64136. return new Promise(function (resolve, reject) {
  64137. BABYLON.Tools.LoadFile(url, function (data) {
  64138. resolve(data);
  64139. }, undefined, undefined, true, function (request, exception) {
  64140. reject(exception);
  64141. });
  64142. });
  64143. };
  64144. /**
  64145. * The configuration. Defaults to the following urls:
  64146. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  64147. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  64148. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64149. */
  64150. DracoCompression.Configuration = {
  64151. decoder: {
  64152. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  64153. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  64154. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64155. }
  64156. };
  64157. return DracoCompression;
  64158. }());
  64159. BABYLON.DracoCompression = DracoCompression;
  64160. })(BABYLON || (BABYLON = {}));
  64161. //# sourceMappingURL=babylon.dracoCompression.js.map
  64162. var BABYLON;
  64163. (function (BABYLON) {
  64164. var AudioEngine = /** @class */ (function () {
  64165. function AudioEngine() {
  64166. this._audioContext = null;
  64167. this._audioContextInitialized = false;
  64168. this.canUseWebAudio = false;
  64169. this.WarnedWebAudioUnsupported = false;
  64170. this.unlocked = false;
  64171. this.isMP3supported = false;
  64172. this.isOGGsupported = false;
  64173. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  64174. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  64175. this.canUseWebAudio = true;
  64176. }
  64177. var audioElem = document.createElement('audio');
  64178. try {
  64179. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  64180. this.isMP3supported = true;
  64181. }
  64182. }
  64183. catch (e) {
  64184. // protect error during capability check.
  64185. }
  64186. try {
  64187. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  64188. this.isOGGsupported = true;
  64189. }
  64190. }
  64191. catch (e) {
  64192. // protect error during capability check.
  64193. }
  64194. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  64195. this._unlockiOSaudio();
  64196. }
  64197. else {
  64198. this.unlocked = true;
  64199. }
  64200. }
  64201. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  64202. get: function () {
  64203. if (!this._audioContextInitialized) {
  64204. this._initializeAudioContext();
  64205. }
  64206. return this._audioContext;
  64207. },
  64208. enumerable: true,
  64209. configurable: true
  64210. });
  64211. AudioEngine.prototype._unlockiOSaudio = function () {
  64212. var _this = this;
  64213. var unlockaudio = function () {
  64214. if (!_this.audioContext) {
  64215. return;
  64216. }
  64217. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  64218. var source = _this.audioContext.createBufferSource();
  64219. source.buffer = buffer;
  64220. source.connect(_this.audioContext.destination);
  64221. source.start(0);
  64222. setTimeout(function () {
  64223. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  64224. _this.unlocked = true;
  64225. window.removeEventListener('touchend', unlockaudio, false);
  64226. if (_this.onAudioUnlocked) {
  64227. _this.onAudioUnlocked();
  64228. }
  64229. }
  64230. }, 0);
  64231. };
  64232. window.addEventListener('touchend', unlockaudio, false);
  64233. };
  64234. AudioEngine.prototype._initializeAudioContext = function () {
  64235. try {
  64236. if (this.canUseWebAudio) {
  64237. this._audioContext = new AudioContext();
  64238. // create a global volume gain node
  64239. this.masterGain = this._audioContext.createGain();
  64240. this.masterGain.gain.value = 1;
  64241. this.masterGain.connect(this._audioContext.destination);
  64242. this._audioContextInitialized = true;
  64243. }
  64244. }
  64245. catch (e) {
  64246. this.canUseWebAudio = false;
  64247. BABYLON.Tools.Error("Web Audio: " + e.message);
  64248. }
  64249. };
  64250. AudioEngine.prototype.dispose = function () {
  64251. if (this.canUseWebAudio && this._audioContextInitialized) {
  64252. if (this._connectedAnalyser && this._audioContext) {
  64253. this._connectedAnalyser.stopDebugCanvas();
  64254. this._connectedAnalyser.dispose();
  64255. this.masterGain.disconnect();
  64256. this.masterGain.connect(this._audioContext.destination);
  64257. this._connectedAnalyser = null;
  64258. }
  64259. this.masterGain.gain.value = 1;
  64260. }
  64261. this.WarnedWebAudioUnsupported = false;
  64262. };
  64263. AudioEngine.prototype.getGlobalVolume = function () {
  64264. if (this.canUseWebAudio && this._audioContextInitialized) {
  64265. return this.masterGain.gain.value;
  64266. }
  64267. else {
  64268. return -1;
  64269. }
  64270. };
  64271. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  64272. if (this.canUseWebAudio && this._audioContextInitialized) {
  64273. this.masterGain.gain.value = newVolume;
  64274. }
  64275. };
  64276. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  64277. if (this._connectedAnalyser) {
  64278. this._connectedAnalyser.stopDebugCanvas();
  64279. }
  64280. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  64281. this._connectedAnalyser = analyser;
  64282. this.masterGain.disconnect();
  64283. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  64284. }
  64285. };
  64286. return AudioEngine;
  64287. }());
  64288. BABYLON.AudioEngine = AudioEngine;
  64289. })(BABYLON || (BABYLON = {}));
  64290. //# sourceMappingURL=babylon.audioEngine.js.map
  64291. var BABYLON;
  64292. (function (BABYLON) {
  64293. var Sound = /** @class */ (function () {
  64294. /**
  64295. * Create a sound and attach it to a scene
  64296. * @param name Name of your sound
  64297. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  64298. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  64299. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  64300. */
  64301. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  64302. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  64303. var _this = this;
  64304. this.autoplay = false;
  64305. this.loop = false;
  64306. this.useCustomAttenuation = false;
  64307. this.spatialSound = false;
  64308. this.refDistance = 1;
  64309. this.rolloffFactor = 1;
  64310. this.maxDistance = 100;
  64311. this.distanceModel = "linear";
  64312. this._panningModel = "equalpower";
  64313. /**
  64314. * Observable event when the current playing sound finishes.
  64315. */
  64316. this.onEndedObservable = new BABYLON.Observable();
  64317. this._playbackRate = 1;
  64318. this._streaming = false;
  64319. this._startTime = 0;
  64320. this._startOffset = 0;
  64321. this._position = BABYLON.Vector3.Zero();
  64322. /** @hidden */
  64323. this._positionInEmitterSpace = false;
  64324. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  64325. this._volume = 1;
  64326. this._isReadyToPlay = false;
  64327. this.isPlaying = false;
  64328. this.isPaused = false;
  64329. this._isDirectional = false;
  64330. // Used if you'd like to create a directional sound.
  64331. // If not set, the sound will be omnidirectional
  64332. this._coneInnerAngle = 360;
  64333. this._coneOuterAngle = 360;
  64334. this._coneOuterGain = 0;
  64335. this._isOutputConnected = false;
  64336. this._urlType = "Unknown";
  64337. this.name = name;
  64338. this._scene = scene;
  64339. this._readyToPlayCallback = readyToPlayCallback;
  64340. // Default custom attenuation function is a linear attenuation
  64341. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  64342. if (currentDistance < maxDistance) {
  64343. return currentVolume * (1 - currentDistance / maxDistance);
  64344. }
  64345. else {
  64346. return 0;
  64347. }
  64348. };
  64349. if (options) {
  64350. this.autoplay = options.autoplay || false;
  64351. this.loop = options.loop || false;
  64352. // if volume === 0, we need another way to check this option
  64353. if (options.volume !== undefined) {
  64354. this._volume = options.volume;
  64355. }
  64356. this.spatialSound = options.spatialSound || false;
  64357. this.maxDistance = options.maxDistance || 100;
  64358. this.useCustomAttenuation = options.useCustomAttenuation || false;
  64359. this.rolloffFactor = options.rolloffFactor || 1;
  64360. this.refDistance = options.refDistance || 1;
  64361. this.distanceModel = options.distanceModel || "linear";
  64362. this._playbackRate = options.playbackRate || 1;
  64363. this._streaming = options.streaming || false;
  64364. }
  64365. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64366. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  64367. this._soundGain.gain.value = this._volume;
  64368. this._inputAudioNode = this._soundGain;
  64369. this._outputAudioNode = this._soundGain;
  64370. if (this.spatialSound) {
  64371. this._createSpatialParameters();
  64372. }
  64373. this._scene.mainSoundTrack.AddSound(this);
  64374. var validParameter = true;
  64375. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  64376. if (urlOrArrayBuffer) {
  64377. try {
  64378. if (typeof (urlOrArrayBuffer) === "string") {
  64379. this._urlType = "String";
  64380. }
  64381. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  64382. this._urlType = "ArrayBuffer";
  64383. }
  64384. else if (urlOrArrayBuffer instanceof MediaStream) {
  64385. this._urlType = "MediaStream";
  64386. }
  64387. else if (Array.isArray(urlOrArrayBuffer)) {
  64388. this._urlType = "Array";
  64389. }
  64390. var urls = [];
  64391. var codecSupportedFound = false;
  64392. switch (this._urlType) {
  64393. case "MediaStream":
  64394. this._streaming = true;
  64395. this._isReadyToPlay = true;
  64396. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  64397. if (this.autoplay) {
  64398. this.play();
  64399. }
  64400. if (this._readyToPlayCallback) {
  64401. this._readyToPlayCallback();
  64402. }
  64403. break;
  64404. case "ArrayBuffer":
  64405. if (urlOrArrayBuffer.byteLength > 0) {
  64406. codecSupportedFound = true;
  64407. this._soundLoaded(urlOrArrayBuffer);
  64408. }
  64409. break;
  64410. case "String":
  64411. urls.push(urlOrArrayBuffer);
  64412. case "Array":
  64413. if (urls.length === 0)
  64414. urls = urlOrArrayBuffer;
  64415. // If we found a supported format, we load it immediately and stop the loop
  64416. for (var i = 0; i < urls.length; i++) {
  64417. var url = urls[i];
  64418. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  64419. codecSupportedFound = true;
  64420. }
  64421. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  64422. codecSupportedFound = true;
  64423. }
  64424. if (url.indexOf(".wav", url.length - 4) !== -1) {
  64425. codecSupportedFound = true;
  64426. }
  64427. if (url.indexOf("blob:") !== -1) {
  64428. codecSupportedFound = true;
  64429. }
  64430. if (codecSupportedFound) {
  64431. // Loading sound using XHR2
  64432. if (!this._streaming) {
  64433. this._scene._loadFile(url, function (data) {
  64434. _this._soundLoaded(data);
  64435. }, undefined, true, true, function (exception) {
  64436. if (exception) {
  64437. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  64438. }
  64439. BABYLON.Tools.Error("Sound creation aborted.");
  64440. _this._scene.mainSoundTrack.RemoveSound(_this);
  64441. });
  64442. }
  64443. // Streaming sound using HTML5 Audio tag
  64444. else {
  64445. this._htmlAudioElement = new Audio(url);
  64446. this._htmlAudioElement.controls = false;
  64447. this._htmlAudioElement.loop = this.loop;
  64448. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  64449. this._htmlAudioElement.preload = "auto";
  64450. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  64451. _this._isReadyToPlay = true;
  64452. if (_this.autoplay) {
  64453. _this.play();
  64454. }
  64455. if (_this._readyToPlayCallback) {
  64456. _this._readyToPlayCallback();
  64457. }
  64458. });
  64459. document.body.appendChild(this._htmlAudioElement);
  64460. }
  64461. break;
  64462. }
  64463. }
  64464. break;
  64465. default:
  64466. validParameter = false;
  64467. break;
  64468. }
  64469. if (!validParameter) {
  64470. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  64471. }
  64472. else {
  64473. if (!codecSupportedFound) {
  64474. this._isReadyToPlay = true;
  64475. // Simulating a ready to play event to avoid breaking code path
  64476. if (this._readyToPlayCallback) {
  64477. window.setTimeout(function () {
  64478. if (_this._readyToPlayCallback) {
  64479. _this._readyToPlayCallback();
  64480. }
  64481. }, 1000);
  64482. }
  64483. }
  64484. }
  64485. }
  64486. catch (ex) {
  64487. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  64488. this._scene.mainSoundTrack.RemoveSound(this);
  64489. }
  64490. }
  64491. }
  64492. else {
  64493. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  64494. this._scene.mainSoundTrack.AddSound(this);
  64495. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  64496. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  64497. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  64498. }
  64499. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  64500. if (this._readyToPlayCallback) {
  64501. window.setTimeout(function () {
  64502. if (_this._readyToPlayCallback) {
  64503. _this._readyToPlayCallback();
  64504. }
  64505. }, 1000);
  64506. }
  64507. }
  64508. }
  64509. Sound.prototype.dispose = function () {
  64510. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64511. if (this.isPlaying) {
  64512. this.stop();
  64513. }
  64514. this._isReadyToPlay = false;
  64515. if (this.soundTrackId === -1) {
  64516. this._scene.mainSoundTrack.RemoveSound(this);
  64517. }
  64518. else {
  64519. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  64520. }
  64521. if (this._soundGain) {
  64522. this._soundGain.disconnect();
  64523. this._soundGain = null;
  64524. }
  64525. if (this._soundPanner) {
  64526. this._soundPanner.disconnect();
  64527. this._soundPanner = null;
  64528. }
  64529. if (this._soundSource) {
  64530. this._soundSource.disconnect();
  64531. this._soundSource = null;
  64532. }
  64533. this._audioBuffer = null;
  64534. if (this._htmlAudioElement) {
  64535. this._htmlAudioElement.pause();
  64536. this._htmlAudioElement.src = "";
  64537. document.body.removeChild(this._htmlAudioElement);
  64538. }
  64539. if (this._streamingSource) {
  64540. this._streamingSource.disconnect();
  64541. }
  64542. if (this._connectedMesh && this._registerFunc) {
  64543. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64544. this._connectedMesh = null;
  64545. }
  64546. }
  64547. };
  64548. Sound.prototype.isReady = function () {
  64549. return this._isReadyToPlay;
  64550. };
  64551. Sound.prototype._soundLoaded = function (audioData) {
  64552. var _this = this;
  64553. if (!BABYLON.Engine.audioEngine.audioContext) {
  64554. return;
  64555. }
  64556. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  64557. _this._audioBuffer = buffer;
  64558. _this._isReadyToPlay = true;
  64559. if (_this.autoplay) {
  64560. _this.play();
  64561. }
  64562. if (_this._readyToPlayCallback) {
  64563. _this._readyToPlayCallback();
  64564. }
  64565. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  64566. };
  64567. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  64568. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64569. this._audioBuffer = audioBuffer;
  64570. this._isReadyToPlay = true;
  64571. }
  64572. };
  64573. Sound.prototype.updateOptions = function (options) {
  64574. if (options) {
  64575. this.loop = options.loop || this.loop;
  64576. this.maxDistance = options.maxDistance || this.maxDistance;
  64577. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  64578. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  64579. this.refDistance = options.refDistance || this.refDistance;
  64580. this.distanceModel = options.distanceModel || this.distanceModel;
  64581. this._playbackRate = options.playbackRate || this._playbackRate;
  64582. this._updateSpatialParameters();
  64583. if (this.isPlaying) {
  64584. if (this._streaming && this._htmlAudioElement) {
  64585. this._htmlAudioElement.playbackRate = this._playbackRate;
  64586. }
  64587. else {
  64588. if (this._soundSource) {
  64589. this._soundSource.playbackRate.value = this._playbackRate;
  64590. }
  64591. }
  64592. }
  64593. }
  64594. };
  64595. Sound.prototype._createSpatialParameters = function () {
  64596. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64597. if (this._scene.headphone) {
  64598. this._panningModel = "HRTF";
  64599. }
  64600. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  64601. this._updateSpatialParameters();
  64602. this._soundPanner.connect(this._outputAudioNode);
  64603. this._inputAudioNode = this._soundPanner;
  64604. }
  64605. };
  64606. Sound.prototype._updateSpatialParameters = function () {
  64607. if (this.spatialSound && this._soundPanner) {
  64608. if (this.useCustomAttenuation) {
  64609. // Tricks to disable in a way embedded Web Audio attenuation
  64610. this._soundPanner.distanceModel = "linear";
  64611. this._soundPanner.maxDistance = Number.MAX_VALUE;
  64612. this._soundPanner.refDistance = 1;
  64613. this._soundPanner.rolloffFactor = 1;
  64614. this._soundPanner.panningModel = this._panningModel;
  64615. }
  64616. else {
  64617. this._soundPanner.distanceModel = this.distanceModel;
  64618. this._soundPanner.maxDistance = this.maxDistance;
  64619. this._soundPanner.refDistance = this.refDistance;
  64620. this._soundPanner.rolloffFactor = this.rolloffFactor;
  64621. this._soundPanner.panningModel = this._panningModel;
  64622. }
  64623. }
  64624. };
  64625. Sound.prototype.switchPanningModelToHRTF = function () {
  64626. this._panningModel = "HRTF";
  64627. this._switchPanningModel();
  64628. };
  64629. Sound.prototype.switchPanningModelToEqualPower = function () {
  64630. this._panningModel = "equalpower";
  64631. this._switchPanningModel();
  64632. };
  64633. Sound.prototype._switchPanningModel = function () {
  64634. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64635. this._soundPanner.panningModel = this._panningModel;
  64636. }
  64637. };
  64638. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  64639. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64640. if (this._isOutputConnected) {
  64641. this._outputAudioNode.disconnect();
  64642. }
  64643. this._outputAudioNode.connect(soundTrackAudioNode);
  64644. this._isOutputConnected = true;
  64645. }
  64646. };
  64647. /**
  64648. * Transform this sound into a directional source
  64649. * @param coneInnerAngle Size of the inner cone in degree
  64650. * @param coneOuterAngle Size of the outer cone in degree
  64651. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  64652. */
  64653. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  64654. if (coneOuterAngle < coneInnerAngle) {
  64655. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  64656. return;
  64657. }
  64658. this._coneInnerAngle = coneInnerAngle;
  64659. this._coneOuterAngle = coneOuterAngle;
  64660. this._coneOuterGain = coneOuterGain;
  64661. this._isDirectional = true;
  64662. if (this.isPlaying && this.loop) {
  64663. this.stop();
  64664. this.play();
  64665. }
  64666. };
  64667. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  64668. /**
  64669. * Gets or sets the inner angle for the directional cone.
  64670. */
  64671. get: function () {
  64672. return this._coneInnerAngle;
  64673. },
  64674. /**
  64675. * Gets or sets the inner angle for the directional cone.
  64676. */
  64677. set: function (value) {
  64678. if (value != this._coneInnerAngle) {
  64679. if (this._coneOuterAngle < value) {
  64680. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  64681. return;
  64682. }
  64683. this._coneInnerAngle = value;
  64684. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64685. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64686. }
  64687. }
  64688. },
  64689. enumerable: true,
  64690. configurable: true
  64691. });
  64692. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  64693. /**
  64694. * Gets or sets the outer angle for the directional cone.
  64695. */
  64696. get: function () {
  64697. return this._coneOuterAngle;
  64698. },
  64699. /**
  64700. * Gets or sets the outer angle for the directional cone.
  64701. */
  64702. set: function (value) {
  64703. if (value != this._coneOuterAngle) {
  64704. if (value < this._coneInnerAngle) {
  64705. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  64706. return;
  64707. }
  64708. this._coneOuterAngle = value;
  64709. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64710. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64711. }
  64712. }
  64713. },
  64714. enumerable: true,
  64715. configurable: true
  64716. });
  64717. Sound.prototype.setPosition = function (newPosition) {
  64718. this._position = newPosition;
  64719. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  64720. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64721. }
  64722. };
  64723. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  64724. this._localDirection = newLocalDirection;
  64725. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  64726. this._updateDirection();
  64727. }
  64728. };
  64729. Sound.prototype._updateDirection = function () {
  64730. if (!this._connectedMesh || !this._soundPanner) {
  64731. return;
  64732. }
  64733. var mat = this._connectedMesh.getWorldMatrix();
  64734. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  64735. direction.normalize();
  64736. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  64737. };
  64738. Sound.prototype.updateDistanceFromListener = function () {
  64739. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  64740. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  64741. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  64742. }
  64743. };
  64744. Sound.prototype.setAttenuationFunction = function (callback) {
  64745. this._customAttenuationFunction = callback;
  64746. };
  64747. /**
  64748. * Play the sound
  64749. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  64750. * @param offset (optional) Start the sound setting it at a specific time
  64751. */
  64752. Sound.prototype.play = function (time, offset) {
  64753. var _this = this;
  64754. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  64755. try {
  64756. if (this._startOffset < 0) {
  64757. time = -this._startOffset;
  64758. this._startOffset = 0;
  64759. }
  64760. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64761. if (!this._soundSource || !this._streamingSource) {
  64762. if (this.spatialSound && this._soundPanner) {
  64763. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  64764. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64765. }
  64766. if (this._isDirectional) {
  64767. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64768. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64769. this._soundPanner.coneOuterGain = this._coneOuterGain;
  64770. if (this._connectedMesh) {
  64771. this._updateDirection();
  64772. }
  64773. else {
  64774. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  64775. }
  64776. }
  64777. }
  64778. }
  64779. if (this._streaming) {
  64780. if (!this._streamingSource) {
  64781. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  64782. this._htmlAudioElement.onended = function () { _this._onended(); };
  64783. this._htmlAudioElement.playbackRate = this._playbackRate;
  64784. }
  64785. this._streamingSource.disconnect();
  64786. this._streamingSource.connect(this._inputAudioNode);
  64787. if (this._htmlAudioElement) {
  64788. this._htmlAudioElement.play();
  64789. }
  64790. }
  64791. else {
  64792. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  64793. this._soundSource.buffer = this._audioBuffer;
  64794. this._soundSource.connect(this._inputAudioNode);
  64795. this._soundSource.loop = this.loop;
  64796. this._soundSource.playbackRate.value = this._playbackRate;
  64797. this._soundSource.onended = function () { _this._onended(); };
  64798. if (this._soundSource.buffer) {
  64799. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  64800. }
  64801. }
  64802. this._startTime = startTime;
  64803. this.isPlaying = true;
  64804. this.isPaused = false;
  64805. }
  64806. catch (ex) {
  64807. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  64808. }
  64809. }
  64810. };
  64811. Sound.prototype._onended = function () {
  64812. this.isPlaying = false;
  64813. if (this.onended) {
  64814. this.onended();
  64815. }
  64816. this.onEndedObservable.notifyObservers(this);
  64817. };
  64818. /**
  64819. * Stop the sound
  64820. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  64821. */
  64822. Sound.prototype.stop = function (time) {
  64823. if (this.isPlaying) {
  64824. if (this._streaming) {
  64825. if (this._htmlAudioElement) {
  64826. this._htmlAudioElement.pause();
  64827. // Test needed for Firefox or it will generate an Invalid State Error
  64828. if (this._htmlAudioElement.currentTime > 0) {
  64829. this._htmlAudioElement.currentTime = 0;
  64830. }
  64831. }
  64832. else {
  64833. this._streamingSource.disconnect();
  64834. }
  64835. }
  64836. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  64837. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64838. this._soundSource.stop(stopTime);
  64839. this._soundSource.onended = function () { };
  64840. if (!this.isPaused) {
  64841. this._startOffset = 0;
  64842. }
  64843. }
  64844. this.isPlaying = false;
  64845. }
  64846. };
  64847. Sound.prototype.pause = function () {
  64848. if (this.isPlaying) {
  64849. this.isPaused = true;
  64850. if (this._streaming) {
  64851. if (this._htmlAudioElement) {
  64852. this._htmlAudioElement.pause();
  64853. }
  64854. else {
  64855. this._streamingSource.disconnect();
  64856. }
  64857. }
  64858. else if (BABYLON.Engine.audioEngine.audioContext) {
  64859. this.stop(0);
  64860. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  64861. }
  64862. }
  64863. };
  64864. Sound.prototype.setVolume = function (newVolume, time) {
  64865. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  64866. if (time && BABYLON.Engine.audioEngine.audioContext) {
  64867. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  64868. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  64869. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  64870. }
  64871. else {
  64872. this._soundGain.gain.value = newVolume;
  64873. }
  64874. }
  64875. this._volume = newVolume;
  64876. };
  64877. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  64878. this._playbackRate = newPlaybackRate;
  64879. if (this.isPlaying) {
  64880. if (this._streaming && this._htmlAudioElement) {
  64881. this._htmlAudioElement.playbackRate = this._playbackRate;
  64882. }
  64883. else if (this._soundSource) {
  64884. this._soundSource.playbackRate.value = this._playbackRate;
  64885. }
  64886. }
  64887. };
  64888. Sound.prototype.getVolume = function () {
  64889. return this._volume;
  64890. };
  64891. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  64892. var _this = this;
  64893. if (this._connectedMesh && this._registerFunc) {
  64894. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64895. this._registerFunc = null;
  64896. }
  64897. this._connectedMesh = meshToConnectTo;
  64898. if (!this.spatialSound) {
  64899. this.spatialSound = true;
  64900. this._createSpatialParameters();
  64901. if (this.isPlaying && this.loop) {
  64902. this.stop();
  64903. this.play();
  64904. }
  64905. }
  64906. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  64907. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  64908. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  64909. };
  64910. Sound.prototype.detachFromMesh = function () {
  64911. if (this._connectedMesh && this._registerFunc) {
  64912. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64913. this._registerFunc = null;
  64914. this._connectedMesh = null;
  64915. }
  64916. };
  64917. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  64918. if (!node.getBoundingInfo) {
  64919. return;
  64920. }
  64921. var mesh = node;
  64922. if (this._positionInEmitterSpace) {
  64923. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  64924. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  64925. }
  64926. else {
  64927. var boundingInfo = mesh.getBoundingInfo();
  64928. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  64929. }
  64930. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  64931. this._updateDirection();
  64932. }
  64933. };
  64934. Sound.prototype.clone = function () {
  64935. var _this = this;
  64936. if (!this._streaming) {
  64937. var setBufferAndRun = function () {
  64938. if (_this._isReadyToPlay) {
  64939. clonedSound._audioBuffer = _this.getAudioBuffer();
  64940. clonedSound._isReadyToPlay = true;
  64941. if (clonedSound.autoplay) {
  64942. clonedSound.play();
  64943. }
  64944. }
  64945. else {
  64946. window.setTimeout(setBufferAndRun, 300);
  64947. }
  64948. };
  64949. var currentOptions = {
  64950. autoplay: this.autoplay, loop: this.loop,
  64951. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  64952. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  64953. refDistance: this.refDistance, distanceModel: this.distanceModel
  64954. };
  64955. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  64956. if (this.useCustomAttenuation) {
  64957. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  64958. }
  64959. clonedSound.setPosition(this._position);
  64960. clonedSound.setPlaybackRate(this._playbackRate);
  64961. setBufferAndRun();
  64962. return clonedSound;
  64963. }
  64964. // Can't clone a streaming sound
  64965. else {
  64966. return null;
  64967. }
  64968. };
  64969. Sound.prototype.getAudioBuffer = function () {
  64970. return this._audioBuffer;
  64971. };
  64972. Sound.prototype.serialize = function () {
  64973. var serializationObject = {
  64974. name: this.name,
  64975. url: this.name,
  64976. autoplay: this.autoplay,
  64977. loop: this.loop,
  64978. volume: this._volume,
  64979. spatialSound: this.spatialSound,
  64980. maxDistance: this.maxDistance,
  64981. rolloffFactor: this.rolloffFactor,
  64982. refDistance: this.refDistance,
  64983. distanceModel: this.distanceModel,
  64984. playbackRate: this._playbackRate,
  64985. panningModel: this._panningModel,
  64986. soundTrackId: this.soundTrackId
  64987. };
  64988. if (this.spatialSound) {
  64989. if (this._connectedMesh)
  64990. serializationObject.connectedMeshId = this._connectedMesh.id;
  64991. serializationObject.position = this._position.asArray();
  64992. serializationObject.refDistance = this.refDistance;
  64993. serializationObject.distanceModel = this.distanceModel;
  64994. serializationObject.isDirectional = this._isDirectional;
  64995. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  64996. serializationObject.coneInnerAngle = this._coneInnerAngle;
  64997. serializationObject.coneOuterAngle = this._coneOuterAngle;
  64998. serializationObject.coneOuterGain = this._coneOuterGain;
  64999. }
  65000. return serializationObject;
  65001. };
  65002. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  65003. var soundName = parsedSound.name;
  65004. var soundUrl;
  65005. if (parsedSound.url) {
  65006. soundUrl = rootUrl + parsedSound.url;
  65007. }
  65008. else {
  65009. soundUrl = rootUrl + soundName;
  65010. }
  65011. var options = {
  65012. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  65013. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  65014. rolloffFactor: parsedSound.rolloffFactor,
  65015. refDistance: parsedSound.refDistance,
  65016. distanceModel: parsedSound.distanceModel,
  65017. playbackRate: parsedSound.playbackRate
  65018. };
  65019. var newSound;
  65020. if (!sourceSound) {
  65021. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  65022. scene._addPendingData(newSound);
  65023. }
  65024. else {
  65025. var setBufferAndRun = function () {
  65026. if (sourceSound._isReadyToPlay) {
  65027. newSound._audioBuffer = sourceSound.getAudioBuffer();
  65028. newSound._isReadyToPlay = true;
  65029. if (newSound.autoplay) {
  65030. newSound.play();
  65031. }
  65032. }
  65033. else {
  65034. window.setTimeout(setBufferAndRun, 300);
  65035. }
  65036. };
  65037. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  65038. setBufferAndRun();
  65039. }
  65040. if (parsedSound.position) {
  65041. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  65042. newSound.setPosition(soundPosition);
  65043. }
  65044. if (parsedSound.isDirectional) {
  65045. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  65046. if (parsedSound.localDirectionToMesh) {
  65047. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  65048. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  65049. }
  65050. }
  65051. if (parsedSound.connectedMeshId) {
  65052. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  65053. if (connectedMesh) {
  65054. newSound.attachToMesh(connectedMesh);
  65055. }
  65056. }
  65057. return newSound;
  65058. };
  65059. return Sound;
  65060. }());
  65061. BABYLON.Sound = Sound;
  65062. })(BABYLON || (BABYLON = {}));
  65063. //# sourceMappingURL=babylon.sound.js.map
  65064. var BABYLON;
  65065. (function (BABYLON) {
  65066. var SoundTrack = /** @class */ (function () {
  65067. function SoundTrack(scene, options) {
  65068. this.id = -1;
  65069. this._isMainTrack = false;
  65070. this._isInitialized = false;
  65071. this._scene = scene;
  65072. this.soundCollection = new Array();
  65073. this._options = options;
  65074. if (!this._isMainTrack) {
  65075. this._scene.soundTracks.push(this);
  65076. this.id = this._scene.soundTracks.length - 1;
  65077. }
  65078. }
  65079. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  65080. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65081. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  65082. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  65083. if (this._options) {
  65084. if (this._options.volume) {
  65085. this._outputAudioNode.gain.value = this._options.volume;
  65086. }
  65087. if (this._options.mainTrack) {
  65088. this._isMainTrack = this._options.mainTrack;
  65089. }
  65090. }
  65091. this._isInitialized = true;
  65092. }
  65093. };
  65094. SoundTrack.prototype.dispose = function () {
  65095. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  65096. if (this._connectedAnalyser) {
  65097. this._connectedAnalyser.stopDebugCanvas();
  65098. }
  65099. while (this.soundCollection.length) {
  65100. this.soundCollection[0].dispose();
  65101. }
  65102. if (this._outputAudioNode) {
  65103. this._outputAudioNode.disconnect();
  65104. }
  65105. this._outputAudioNode = null;
  65106. }
  65107. };
  65108. SoundTrack.prototype.AddSound = function (sound) {
  65109. if (!this._isInitialized) {
  65110. this._initializeSoundTrackAudioGraph();
  65111. }
  65112. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65113. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  65114. }
  65115. if (sound.soundTrackId) {
  65116. if (sound.soundTrackId === -1) {
  65117. this._scene.mainSoundTrack.RemoveSound(sound);
  65118. }
  65119. else {
  65120. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  65121. }
  65122. }
  65123. this.soundCollection.push(sound);
  65124. sound.soundTrackId = this.id;
  65125. };
  65126. SoundTrack.prototype.RemoveSound = function (sound) {
  65127. var index = this.soundCollection.indexOf(sound);
  65128. if (index !== -1) {
  65129. this.soundCollection.splice(index, 1);
  65130. }
  65131. };
  65132. SoundTrack.prototype.setVolume = function (newVolume) {
  65133. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65134. this._outputAudioNode.gain.value = newVolume;
  65135. }
  65136. };
  65137. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  65138. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65139. for (var i = 0; i < this.soundCollection.length; i++) {
  65140. this.soundCollection[i].switchPanningModelToHRTF();
  65141. }
  65142. }
  65143. };
  65144. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  65145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65146. for (var i = 0; i < this.soundCollection.length; i++) {
  65147. this.soundCollection[i].switchPanningModelToEqualPower();
  65148. }
  65149. }
  65150. };
  65151. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  65152. if (this._connectedAnalyser) {
  65153. this._connectedAnalyser.stopDebugCanvas();
  65154. }
  65155. this._connectedAnalyser = analyser;
  65156. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65157. this._outputAudioNode.disconnect();
  65158. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  65159. }
  65160. };
  65161. return SoundTrack;
  65162. }());
  65163. BABYLON.SoundTrack = SoundTrack;
  65164. })(BABYLON || (BABYLON = {}));
  65165. //# sourceMappingURL=babylon.soundtrack.js.map
  65166. var BABYLON;
  65167. (function (BABYLON) {
  65168. /**
  65169. * Class used to work with sound analyzer using fast fourier transform (FFT)
  65170. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  65171. */
  65172. var Analyser = /** @class */ (function () {
  65173. /**
  65174. * Creates a new analyser
  65175. * @param scene defines hosting scene
  65176. */
  65177. function Analyser(scene) {
  65178. /**
  65179. * Gets or sets the smoothing
  65180. * @ignorenaming
  65181. */
  65182. this.SMOOTHING = 0.75;
  65183. /**
  65184. * Gets or sets the FFT table size
  65185. * @ignorenaming
  65186. */
  65187. this.FFT_SIZE = 512;
  65188. /**
  65189. * Gets or sets the bar graph amplitude
  65190. * @ignorenaming
  65191. */
  65192. this.BARGRAPHAMPLITUDE = 256;
  65193. /**
  65194. * Gets or sets the position of the debug canvas
  65195. * @ignorenaming
  65196. */
  65197. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  65198. /**
  65199. * Gets or sets the debug canvas size
  65200. * @ignorenaming
  65201. */
  65202. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  65203. this._scene = scene;
  65204. this._audioEngine = BABYLON.Engine.audioEngine;
  65205. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  65206. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  65207. this._webAudioAnalyser.minDecibels = -140;
  65208. this._webAudioAnalyser.maxDecibels = 0;
  65209. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65210. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65211. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  65212. }
  65213. }
  65214. /**
  65215. * Get the number of data values you will have to play with for the visualization
  65216. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  65217. * @returns a number
  65218. */
  65219. Analyser.prototype.getFrequencyBinCount = function () {
  65220. if (this._audioEngine.canUseWebAudio) {
  65221. return this._webAudioAnalyser.frequencyBinCount;
  65222. }
  65223. else {
  65224. return 0;
  65225. }
  65226. };
  65227. /**
  65228. * Gets the current frequency data as a byte array
  65229. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65230. * @returns a Uint8Array
  65231. */
  65232. Analyser.prototype.getByteFrequencyData = function () {
  65233. if (this._audioEngine.canUseWebAudio) {
  65234. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65235. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65236. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  65237. }
  65238. return this._byteFreqs;
  65239. };
  65240. /**
  65241. * Gets the current waveform as a byte array
  65242. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  65243. * @returns a Uint8Array
  65244. */
  65245. Analyser.prototype.getByteTimeDomainData = function () {
  65246. if (this._audioEngine.canUseWebAudio) {
  65247. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65248. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65249. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  65250. }
  65251. return this._byteTime;
  65252. };
  65253. /**
  65254. * Gets the current frequency data as a float array
  65255. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65256. * @returns a Float32Array
  65257. */
  65258. Analyser.prototype.getFloatFrequencyData = function () {
  65259. if (this._audioEngine.canUseWebAudio) {
  65260. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65261. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65262. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  65263. }
  65264. return this._floatFreqs;
  65265. };
  65266. /**
  65267. * Renders the debug canvas
  65268. */
  65269. Analyser.prototype.drawDebugCanvas = function () {
  65270. var _this = this;
  65271. if (this._audioEngine.canUseWebAudio) {
  65272. if (!this._debugCanvas) {
  65273. this._debugCanvas = document.createElement("canvas");
  65274. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  65275. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  65276. this._debugCanvas.style.position = "absolute";
  65277. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  65278. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  65279. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  65280. document.body.appendChild(this._debugCanvas);
  65281. this._registerFunc = function () {
  65282. _this.drawDebugCanvas();
  65283. };
  65284. this._scene.registerBeforeRender(this._registerFunc);
  65285. }
  65286. if (this._registerFunc && this._debugCanvasContext) {
  65287. var workingArray = this.getByteFrequencyData();
  65288. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  65289. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  65290. // Draw the frequency domain chart.
  65291. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  65292. var value = workingArray[i];
  65293. var percent = value / this.BARGRAPHAMPLITUDE;
  65294. var height = this.DEBUGCANVASSIZE.height * percent;
  65295. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  65296. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  65297. var hue = i / this.getFrequencyBinCount() * 360;
  65298. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  65299. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  65300. }
  65301. }
  65302. }
  65303. };
  65304. /**
  65305. * Stops rendering the debug canvas and removes it
  65306. */
  65307. Analyser.prototype.stopDebugCanvas = function () {
  65308. if (this._debugCanvas) {
  65309. if (this._registerFunc) {
  65310. this._scene.unregisterBeforeRender(this._registerFunc);
  65311. this._registerFunc = null;
  65312. }
  65313. document.body.removeChild(this._debugCanvas);
  65314. this._debugCanvas = null;
  65315. this._debugCanvasContext = null;
  65316. }
  65317. };
  65318. /**
  65319. * Connects two audio nodes
  65320. * @param inputAudioNode defines first node to connect
  65321. * @param outputAudioNode defines second node to connect
  65322. */
  65323. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  65324. if (this._audioEngine.canUseWebAudio) {
  65325. inputAudioNode.connect(this._webAudioAnalyser);
  65326. this._webAudioAnalyser.connect(outputAudioNode);
  65327. }
  65328. };
  65329. /**
  65330. * Releases all associated resources
  65331. */
  65332. Analyser.prototype.dispose = function () {
  65333. if (this._audioEngine.canUseWebAudio) {
  65334. this._webAudioAnalyser.disconnect();
  65335. }
  65336. };
  65337. return Analyser;
  65338. }());
  65339. BABYLON.Analyser = Analyser;
  65340. })(BABYLON || (BABYLON = {}));
  65341. //# sourceMappingURL=babylon.analyser.js.map
  65342. var BABYLON;
  65343. (function (BABYLON) {
  65344. /**
  65345. * Wraps one or more Sound objects and selects one with random weight for playback.
  65346. */
  65347. var WeightedSound = /** @class */ (function () {
  65348. /**
  65349. * Creates a new WeightedSound from the list of sounds given.
  65350. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  65351. * @param sounds Array of Sounds that will be selected from.
  65352. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  65353. */
  65354. function WeightedSound(loop, sounds, weights) {
  65355. var _this = this;
  65356. /** When true a Sound will be selected and played when the current playing Sound completes. */
  65357. this.loop = false;
  65358. this._coneInnerAngle = 360;
  65359. this._coneOuterAngle = 360;
  65360. this._volume = 1;
  65361. /** A Sound is currently playing. */
  65362. this.isPlaying = false;
  65363. /** A Sound is currently paused. */
  65364. this.isPaused = false;
  65365. this._sounds = [];
  65366. this._weights = [];
  65367. if (sounds.length !== weights.length) {
  65368. throw new Error('Sounds length does not equal weights length');
  65369. }
  65370. this.loop = loop;
  65371. this._weights = weights;
  65372. // Normalize the weights
  65373. var weightSum = 0;
  65374. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  65375. var weight = weights_1[_i];
  65376. weightSum += weight;
  65377. }
  65378. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  65379. for (var i = 0; i < this._weights.length; i++) {
  65380. this._weights[i] *= invWeightSum;
  65381. }
  65382. this._sounds = sounds;
  65383. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  65384. var sound = _b[_a];
  65385. sound.onEndedObservable.add(function () { _this._onended(); });
  65386. }
  65387. }
  65388. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  65389. /**
  65390. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  65391. */
  65392. get: function () {
  65393. return this._coneInnerAngle;
  65394. },
  65395. /**
  65396. * The size of cone in degress for a directional sound in which there will be no attenuation.
  65397. */
  65398. set: function (value) {
  65399. if (value !== this._coneInnerAngle) {
  65400. if (this._coneOuterAngle < value) {
  65401. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65402. return;
  65403. }
  65404. this._coneInnerAngle = value;
  65405. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65406. var sound = _a[_i];
  65407. sound.directionalConeInnerAngle = value;
  65408. }
  65409. }
  65410. },
  65411. enumerable: true,
  65412. configurable: true
  65413. });
  65414. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  65415. /**
  65416. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65417. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65418. */
  65419. get: function () {
  65420. return this._coneOuterAngle;
  65421. },
  65422. /**
  65423. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65424. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65425. */
  65426. set: function (value) {
  65427. if (value !== this._coneOuterAngle) {
  65428. if (value < this._coneInnerAngle) {
  65429. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65430. return;
  65431. }
  65432. this._coneOuterAngle = value;
  65433. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65434. var sound = _a[_i];
  65435. sound.directionalConeOuterAngle = value;
  65436. }
  65437. }
  65438. },
  65439. enumerable: true,
  65440. configurable: true
  65441. });
  65442. Object.defineProperty(WeightedSound.prototype, "volume", {
  65443. /**
  65444. * Playback volume.
  65445. */
  65446. get: function () {
  65447. return this._volume;
  65448. },
  65449. /**
  65450. * Playback volume.
  65451. */
  65452. set: function (value) {
  65453. if (value !== this._volume) {
  65454. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65455. var sound = _a[_i];
  65456. sound.setVolume(value);
  65457. }
  65458. }
  65459. },
  65460. enumerable: true,
  65461. configurable: true
  65462. });
  65463. WeightedSound.prototype._onended = function () {
  65464. if (this._currentIndex !== undefined) {
  65465. this._sounds[this._currentIndex].autoplay = false;
  65466. }
  65467. if (this.loop && this.isPlaying) {
  65468. this.play();
  65469. }
  65470. else {
  65471. this.isPlaying = false;
  65472. }
  65473. };
  65474. /**
  65475. * Suspend playback
  65476. */
  65477. WeightedSound.prototype.pause = function () {
  65478. this.isPaused = true;
  65479. if (this._currentIndex !== undefined) {
  65480. this._sounds[this._currentIndex].pause();
  65481. }
  65482. };
  65483. /**
  65484. * Stop playback
  65485. */
  65486. WeightedSound.prototype.stop = function () {
  65487. this.isPlaying = false;
  65488. if (this._currentIndex !== undefined) {
  65489. this._sounds[this._currentIndex].stop();
  65490. }
  65491. };
  65492. /**
  65493. * Start playback.
  65494. * @param startOffset Position the clip head at a specific time in seconds.
  65495. */
  65496. WeightedSound.prototype.play = function (startOffset) {
  65497. if (!this.isPaused) {
  65498. this.stop();
  65499. var randomValue = Math.random();
  65500. var total = 0;
  65501. for (var i = 0; i < this._weights.length; i++) {
  65502. total += this._weights[i];
  65503. if (randomValue <= total) {
  65504. this._currentIndex = i;
  65505. break;
  65506. }
  65507. }
  65508. }
  65509. var sound = this._sounds[this._currentIndex];
  65510. if (sound.isReady()) {
  65511. sound.play(0, this.isPaused ? undefined : startOffset);
  65512. }
  65513. else {
  65514. sound.autoplay = true;
  65515. }
  65516. this.isPlaying = true;
  65517. this.isPaused = false;
  65518. };
  65519. return WeightedSound;
  65520. }());
  65521. BABYLON.WeightedSound = WeightedSound;
  65522. })(BABYLON || (BABYLON = {}));
  65523. //# sourceMappingURL=babylon.weightedsound.js.map
  65524. var BABYLON;
  65525. (function (BABYLON) {
  65526. var CubeTexture = /** @class */ (function (_super) {
  65527. __extends(CubeTexture, _super);
  65528. /**
  65529. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  65530. * as prefiltered data.
  65531. * @param rootUrl defines the url of the texture or the root name of the six images
  65532. * @param scene defines the scene the texture is attached to
  65533. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  65534. * @param noMipmap defines if mipmaps should be created or not
  65535. * @param files defines the six files to load for the different faces
  65536. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  65537. * @param onError defines a callback triggered in case of error during load
  65538. * @param format defines the internal format to use for the texture once loaded
  65539. * @param prefiltered defines whether or not the texture is created from prefiltered data
  65540. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  65541. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65542. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  65543. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  65544. * @return the cube texture
  65545. */
  65546. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  65547. if (extensions === void 0) { extensions = null; }
  65548. if (noMipmap === void 0) { noMipmap = false; }
  65549. if (files === void 0) { files = null; }
  65550. if (onLoad === void 0) { onLoad = null; }
  65551. if (onError === void 0) { onError = null; }
  65552. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65553. if (prefiltered === void 0) { prefiltered = false; }
  65554. if (forcedExtension === void 0) { forcedExtension = null; }
  65555. if (createPolynomials === void 0) { createPolynomials = false; }
  65556. if (lodScale === void 0) { lodScale = 0.8; }
  65557. if (lodOffset === void 0) { lodOffset = 0; }
  65558. var _this = _super.call(this, scene) || this;
  65559. /**
  65560. * Gets or sets the center of the bounding box associated with the cube texture
  65561. * It must define where the camera used to render the texture was set
  65562. */
  65563. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65564. _this._rotationY = 0;
  65565. /** @hidden */
  65566. _this._prefiltered = false;
  65567. _this.name = rootUrl;
  65568. _this.url = rootUrl;
  65569. _this._noMipmap = noMipmap;
  65570. _this.hasAlpha = false;
  65571. _this._format = format;
  65572. _this.isCube = true;
  65573. _this._textureMatrix = BABYLON.Matrix.Identity();
  65574. _this._createPolynomials = createPolynomials;
  65575. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65576. if (!rootUrl && !files) {
  65577. return _this;
  65578. }
  65579. var lastDot = rootUrl.lastIndexOf(".");
  65580. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  65581. var isDDS = (extension === ".dds");
  65582. var isEnv = (extension === ".env");
  65583. if (isEnv) {
  65584. _this.gammaSpace = false;
  65585. _this._prefiltered = false;
  65586. }
  65587. else {
  65588. _this._prefiltered = prefiltered;
  65589. if (prefiltered) {
  65590. _this.gammaSpace = false;
  65591. }
  65592. }
  65593. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  65594. if (!files) {
  65595. if (!isEnv && !isDDS && !extensions) {
  65596. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  65597. }
  65598. files = [];
  65599. if (extensions) {
  65600. for (var index = 0; index < extensions.length; index++) {
  65601. files.push(rootUrl + extensions[index]);
  65602. }
  65603. }
  65604. }
  65605. _this._files = files;
  65606. if (!_this._texture) {
  65607. if (!scene.useDelayedTextureLoading) {
  65608. if (prefiltered) {
  65609. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  65610. }
  65611. else {
  65612. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  65613. }
  65614. }
  65615. else {
  65616. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65617. }
  65618. }
  65619. else if (onLoad) {
  65620. if (_this._texture.isReady) {
  65621. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  65622. }
  65623. else {
  65624. _this._texture.onLoadedObservable.add(onLoad);
  65625. }
  65626. }
  65627. return _this;
  65628. }
  65629. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  65630. get: function () {
  65631. return this._boundingBoxSize;
  65632. },
  65633. /**
  65634. * Gets or sets the size of the bounding box associated with the cube texture
  65635. * When defined, the cubemap will switch to local mode
  65636. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65637. * @example https://www.babylonjs-playground.com/#RNASML
  65638. */
  65639. set: function (value) {
  65640. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65641. return;
  65642. }
  65643. this._boundingBoxSize = value;
  65644. var scene = this.getScene();
  65645. if (scene) {
  65646. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65647. }
  65648. },
  65649. enumerable: true,
  65650. configurable: true
  65651. });
  65652. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  65653. /**
  65654. * Gets texture matrix rotation angle around Y axis radians.
  65655. */
  65656. get: function () {
  65657. return this._rotationY;
  65658. },
  65659. /**
  65660. * Sets texture matrix rotation angle around Y axis in radians.
  65661. */
  65662. set: function (value) {
  65663. this._rotationY = value;
  65664. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  65665. },
  65666. enumerable: true,
  65667. configurable: true
  65668. });
  65669. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  65670. var rootUrlKey = "";
  65671. files.forEach(function (url) { return rootUrlKey += url; });
  65672. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  65673. };
  65674. /**
  65675. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  65676. * @param url defines the url of the prefiltered texture
  65677. * @param scene defines the scene the texture is attached to
  65678. * @param forcedExtension defines the extension of the file if different from the url
  65679. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65680. * @return the prefiltered texture
  65681. */
  65682. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  65683. if (forcedExtension === void 0) { forcedExtension = null; }
  65684. if (createPolynomials === void 0) { createPolynomials = true; }
  65685. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  65686. };
  65687. // Methods
  65688. CubeTexture.prototype.delayLoad = function () {
  65689. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65690. return;
  65691. }
  65692. var scene = this.getScene();
  65693. if (!scene) {
  65694. return;
  65695. }
  65696. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65697. this._texture = this._getFromCache(this.url, this._noMipmap);
  65698. if (!this._texture) {
  65699. if (this._prefiltered) {
  65700. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  65701. }
  65702. else {
  65703. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  65704. }
  65705. }
  65706. };
  65707. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  65708. return this._textureMatrix;
  65709. };
  65710. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  65711. this._textureMatrix = value;
  65712. };
  65713. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65714. var texture = BABYLON.SerializationHelper.Parse(function () {
  65715. var prefiltered = false;
  65716. if (parsedTexture.prefiltered) {
  65717. prefiltered = parsedTexture.prefiltered;
  65718. }
  65719. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  65720. }, parsedTexture, scene);
  65721. // Local Cubemaps
  65722. if (parsedTexture.boundingBoxPosition) {
  65723. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  65724. }
  65725. if (parsedTexture.boundingBoxSize) {
  65726. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  65727. }
  65728. // Animations
  65729. if (parsedTexture.animations) {
  65730. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  65731. var parsedAnimation = parsedTexture.animations[animationIndex];
  65732. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  65733. }
  65734. }
  65735. return texture;
  65736. };
  65737. CubeTexture.prototype.clone = function () {
  65738. var _this = this;
  65739. return BABYLON.SerializationHelper.Clone(function () {
  65740. var scene = _this.getScene();
  65741. if (!scene) {
  65742. return _this;
  65743. }
  65744. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  65745. }, this);
  65746. };
  65747. __decorate([
  65748. BABYLON.serialize("rotationY")
  65749. ], CubeTexture.prototype, "_rotationY", void 0);
  65750. return CubeTexture;
  65751. }(BABYLON.BaseTexture));
  65752. BABYLON.CubeTexture = CubeTexture;
  65753. })(BABYLON || (BABYLON = {}));
  65754. //# sourceMappingURL=babylon.cubeTexture.js.map
  65755. var BABYLON;
  65756. (function (BABYLON) {
  65757. /**
  65758. * Raw cube texture where the raw buffers are passed in
  65759. */
  65760. var RawCubeTexture = /** @class */ (function (_super) {
  65761. __extends(RawCubeTexture, _super);
  65762. /**
  65763. * Creates a cube texture where the raw buffers are passed in.
  65764. * @param scene defines the scene the texture is attached to
  65765. * @param data defines the array of data to use to create each face
  65766. * @param size defines the size of the textures
  65767. * @param format defines the format of the data
  65768. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  65769. * @param generateMipMaps defines if the engine should generate the mip levels
  65770. * @param invertY defines if data must be stored with Y axis inverted
  65771. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  65772. * @param compression defines the compression used (null by default)
  65773. */
  65774. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  65775. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65776. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65777. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65778. if (invertY === void 0) { invertY = false; }
  65779. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65780. if (compression === void 0) { compression = null; }
  65781. var _this = _super.call(this, "", scene) || this;
  65782. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  65783. return _this;
  65784. }
  65785. /**
  65786. * Updates the raw cube texture.
  65787. * @param data defines the data to store
  65788. * @param format defines the data format
  65789. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  65790. * @param invertY defines if data must be stored with Y axis inverted
  65791. * @param compression defines the compression used (null by default)
  65792. * @param level defines which level of the texture to update
  65793. */
  65794. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  65795. if (compression === void 0) { compression = null; }
  65796. if (level === void 0) { level = 0; }
  65797. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  65798. };
  65799. /**
  65800. * Updates a raw cube texture with RGBD encoded data.
  65801. * @param data defines the array of data [mipmap][face] to use to create each face
  65802. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  65803. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  65804. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  65805. * @returns a promsie that resolves when the operation is complete
  65806. */
  65807. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  65808. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  65809. if (lodScale === void 0) { lodScale = 0.8; }
  65810. if (lodOffset === void 0) { lodOffset = 0; }
  65811. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  65812. };
  65813. /**
  65814. * Clones the raw cube texture.
  65815. * @return a new cube texture
  65816. */
  65817. RawCubeTexture.prototype.clone = function () {
  65818. var _this = this;
  65819. return BABYLON.SerializationHelper.Clone(function () {
  65820. var scene = _this.getScene();
  65821. var internalTexture = _this._texture;
  65822. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  65823. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  65824. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  65825. }
  65826. return texture;
  65827. }, this);
  65828. };
  65829. /** @hidden */
  65830. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  65831. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  65832. internalTexture._bufferViewArrayArray = data;
  65833. internalTexture._lodGenerationScale = lodScale;
  65834. internalTexture._lodGenerationOffset = lodOffset;
  65835. internalTexture._sphericalPolynomial = sphericalPolynomial;
  65836. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  65837. internalTexture.isReady = true;
  65838. });
  65839. };
  65840. return RawCubeTexture;
  65841. }(BABYLON.CubeTexture));
  65842. BABYLON.RawCubeTexture = RawCubeTexture;
  65843. })(BABYLON || (BABYLON = {}));
  65844. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  65845. var BABYLON;
  65846. (function (BABYLON) {
  65847. var RenderTargetTexture = /** @class */ (function (_super) {
  65848. __extends(RenderTargetTexture, _super);
  65849. /**
  65850. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  65851. * or used a shadow, depth texture...
  65852. * @param name The friendly name of the texture
  65853. * @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)
  65854. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  65855. * @param generateMipMaps True if mip maps need to be generated after render.
  65856. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  65857. * @param type The type of the buffer in the RTT (int, half float, float...)
  65858. * @param isCube True if a cube texture needs to be created
  65859. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  65860. * @param generateDepthBuffer True to generate a depth buffer
  65861. * @param generateStencilBuffer True to generate a stencil buffer
  65862. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  65863. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  65864. */
  65865. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  65866. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  65867. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65868. if (isCube === void 0) { isCube = false; }
  65869. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65870. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65871. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  65872. if (isMulti === void 0) { isMulti = false; }
  65873. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65874. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65875. _this.isCube = isCube;
  65876. _this.renderParticles = true;
  65877. _this.renderSprites = false;
  65878. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  65879. _this.ignoreCameraViewport = false;
  65880. // Events
  65881. /**
  65882. * An event triggered when the texture is unbind.
  65883. */
  65884. _this.onBeforeBindObservable = new BABYLON.Observable();
  65885. /**
  65886. * An event triggered when the texture is unbind.
  65887. */
  65888. _this.onAfterUnbindObservable = new BABYLON.Observable();
  65889. /**
  65890. * An event triggered before rendering the texture
  65891. */
  65892. _this.onBeforeRenderObservable = new BABYLON.Observable();
  65893. /**
  65894. * An event triggered after rendering the texture
  65895. */
  65896. _this.onAfterRenderObservable = new BABYLON.Observable();
  65897. /**
  65898. * An event triggered after the texture clear
  65899. */
  65900. _this.onClearObservable = new BABYLON.Observable();
  65901. _this._currentRefreshId = -1;
  65902. _this._refreshRate = 1;
  65903. _this._samples = 1;
  65904. /**
  65905. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  65906. * It must define where the camera used to render the texture is set
  65907. */
  65908. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65909. scene = _this.getScene();
  65910. if (!scene) {
  65911. return _this;
  65912. }
  65913. _this.renderList = new Array();
  65914. _this._engine = scene.getEngine();
  65915. _this.name = name;
  65916. _this.isRenderTarget = true;
  65917. _this._initialSizeParameter = size;
  65918. _this._processSizeParameter(size);
  65919. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  65920. });
  65921. _this._generateMipMaps = generateMipMaps ? true : false;
  65922. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  65923. // Rendering groups
  65924. _this._renderingManager = new BABYLON.RenderingManager(scene);
  65925. _this._renderingManager._useSceneAutoClearSetup = true;
  65926. if (isMulti) {
  65927. return _this;
  65928. }
  65929. _this._renderTargetOptions = {
  65930. generateMipMaps: generateMipMaps,
  65931. type: type,
  65932. format: format,
  65933. samplingMode: samplingMode,
  65934. generateDepthBuffer: generateDepthBuffer,
  65935. generateStencilBuffer: generateStencilBuffer
  65936. };
  65937. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  65938. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65939. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65940. }
  65941. if (isCube) {
  65942. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  65943. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  65944. _this._textureMatrix = BABYLON.Matrix.Identity();
  65945. }
  65946. else {
  65947. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  65948. }
  65949. return _this;
  65950. }
  65951. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  65952. get: function () {
  65953. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  65954. },
  65955. enumerable: true,
  65956. configurable: true
  65957. });
  65958. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  65959. get: function () {
  65960. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  65961. },
  65962. enumerable: true,
  65963. configurable: true
  65964. });
  65965. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  65966. get: function () {
  65967. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  65968. },
  65969. enumerable: true,
  65970. configurable: true
  65971. });
  65972. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  65973. /**
  65974. * Use this list to define the list of mesh you want to render.
  65975. */
  65976. get: function () {
  65977. return this._renderList;
  65978. },
  65979. set: function (value) {
  65980. this._renderList = value;
  65981. if (this._renderList) {
  65982. this._hookArray(this._renderList);
  65983. }
  65984. },
  65985. enumerable: true,
  65986. configurable: true
  65987. });
  65988. RenderTargetTexture.prototype._hookArray = function (array) {
  65989. var _this = this;
  65990. var oldPush = array.push;
  65991. array.push = function () {
  65992. var items = [];
  65993. for (var _i = 0; _i < arguments.length; _i++) {
  65994. items[_i] = arguments[_i];
  65995. }
  65996. var result = oldPush.apply(array, items);
  65997. _this.getScene().meshes.forEach(function (mesh) {
  65998. mesh._markSubMeshesAsLightDirty();
  65999. });
  66000. return result;
  66001. };
  66002. var oldSplice = array.splice;
  66003. array.splice = function (index, deleteCount) {
  66004. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66005. _this.getScene().meshes.forEach(function (mesh) {
  66006. mesh._markSubMeshesAsLightDirty();
  66007. });
  66008. return deleted;
  66009. };
  66010. };
  66011. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  66012. set: function (callback) {
  66013. if (this._onAfterUnbindObserver) {
  66014. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  66015. }
  66016. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  66017. },
  66018. enumerable: true,
  66019. configurable: true
  66020. });
  66021. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  66022. set: function (callback) {
  66023. if (this._onBeforeRenderObserver) {
  66024. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66025. }
  66026. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66027. },
  66028. enumerable: true,
  66029. configurable: true
  66030. });
  66031. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  66032. set: function (callback) {
  66033. if (this._onAfterRenderObserver) {
  66034. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66035. }
  66036. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66037. },
  66038. enumerable: true,
  66039. configurable: true
  66040. });
  66041. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  66042. set: function (callback) {
  66043. if (this._onClearObserver) {
  66044. this.onClearObservable.remove(this._onClearObserver);
  66045. }
  66046. this._onClearObserver = this.onClearObservable.add(callback);
  66047. },
  66048. enumerable: true,
  66049. configurable: true
  66050. });
  66051. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  66052. get: function () {
  66053. return this._renderTargetOptions;
  66054. },
  66055. enumerable: true,
  66056. configurable: true
  66057. });
  66058. RenderTargetTexture.prototype._onRatioRescale = function () {
  66059. if (this._sizeRatio) {
  66060. this.resize(this._initialSizeParameter);
  66061. }
  66062. };
  66063. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  66064. get: function () {
  66065. return this._boundingBoxSize;
  66066. },
  66067. /**
  66068. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  66069. * When defined, the cubemap will switch to local mode
  66070. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66071. * @example https://www.babylonjs-playground.com/#RNASML
  66072. */
  66073. set: function (value) {
  66074. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66075. return;
  66076. }
  66077. this._boundingBoxSize = value;
  66078. var scene = this.getScene();
  66079. if (scene) {
  66080. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66081. }
  66082. },
  66083. enumerable: true,
  66084. configurable: true
  66085. });
  66086. /**
  66087. * Creates a depth stencil texture.
  66088. * This is only available in WebGL 2 or with the depth texture extension available.
  66089. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  66090. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  66091. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  66092. */
  66093. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  66094. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  66095. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  66096. if (generateStencil === void 0) { generateStencil = false; }
  66097. if (!this.getScene()) {
  66098. return;
  66099. }
  66100. var engine = this.getScene().getEngine();
  66101. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  66102. bilinearFiltering: bilinearFiltering,
  66103. comparisonFunction: comparisonFunction,
  66104. generateStencil: generateStencil,
  66105. isCube: this.isCube
  66106. });
  66107. engine.setFrameBufferDepthStencilTexture(this);
  66108. };
  66109. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  66110. if (size.ratio) {
  66111. this._sizeRatio = size.ratio;
  66112. this._size = {
  66113. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  66114. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  66115. };
  66116. }
  66117. else {
  66118. this._size = size;
  66119. }
  66120. };
  66121. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  66122. get: function () {
  66123. return this._samples;
  66124. },
  66125. set: function (value) {
  66126. if (this._samples === value) {
  66127. return;
  66128. }
  66129. var scene = this.getScene();
  66130. if (!scene) {
  66131. return;
  66132. }
  66133. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  66134. },
  66135. enumerable: true,
  66136. configurable: true
  66137. });
  66138. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  66139. this._currentRefreshId = -1;
  66140. };
  66141. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  66142. get: function () {
  66143. return this._refreshRate;
  66144. },
  66145. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  66146. set: function (value) {
  66147. this._refreshRate = value;
  66148. this.resetRefreshCounter();
  66149. },
  66150. enumerable: true,
  66151. configurable: true
  66152. });
  66153. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  66154. if (!this._postProcessManager) {
  66155. var scene = this.getScene();
  66156. if (!scene) {
  66157. return;
  66158. }
  66159. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  66160. this._postProcesses = new Array();
  66161. }
  66162. this._postProcesses.push(postProcess);
  66163. this._postProcesses[0].autoClear = false;
  66164. };
  66165. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  66166. if (!this._postProcesses) {
  66167. return;
  66168. }
  66169. if (dispose) {
  66170. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  66171. var postProcess = _a[_i];
  66172. postProcess.dispose();
  66173. }
  66174. }
  66175. this._postProcesses = [];
  66176. };
  66177. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  66178. if (!this._postProcesses) {
  66179. return;
  66180. }
  66181. var index = this._postProcesses.indexOf(postProcess);
  66182. if (index === -1) {
  66183. return;
  66184. }
  66185. this._postProcesses.splice(index, 1);
  66186. if (this._postProcesses.length > 0) {
  66187. this._postProcesses[0].autoClear = false;
  66188. }
  66189. };
  66190. /** @hidden */
  66191. RenderTargetTexture.prototype._shouldRender = function () {
  66192. if (this._currentRefreshId === -1) { // At least render once
  66193. this._currentRefreshId = 1;
  66194. return true;
  66195. }
  66196. if (this.refreshRate === this._currentRefreshId) {
  66197. this._currentRefreshId = 1;
  66198. return true;
  66199. }
  66200. this._currentRefreshId++;
  66201. return false;
  66202. };
  66203. RenderTargetTexture.prototype.getRenderSize = function () {
  66204. if (this._size.width) {
  66205. return this._size.width;
  66206. }
  66207. return this._size;
  66208. };
  66209. RenderTargetTexture.prototype.getRenderWidth = function () {
  66210. if (this._size.width) {
  66211. return this._size.width;
  66212. }
  66213. return this._size;
  66214. };
  66215. RenderTargetTexture.prototype.getRenderHeight = function () {
  66216. if (this._size.width) {
  66217. return this._size.height;
  66218. }
  66219. return this._size;
  66220. };
  66221. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  66222. get: function () {
  66223. return true;
  66224. },
  66225. enumerable: true,
  66226. configurable: true
  66227. });
  66228. RenderTargetTexture.prototype.scale = function (ratio) {
  66229. var newSize = this.getRenderSize() * ratio;
  66230. this.resize(newSize);
  66231. };
  66232. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  66233. if (this.isCube) {
  66234. return this._textureMatrix;
  66235. }
  66236. return _super.prototype.getReflectionTextureMatrix.call(this);
  66237. };
  66238. RenderTargetTexture.prototype.resize = function (size) {
  66239. this.releaseInternalTexture();
  66240. var scene = this.getScene();
  66241. if (!scene) {
  66242. return;
  66243. }
  66244. this._processSizeParameter(size);
  66245. if (this.isCube) {
  66246. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  66247. }
  66248. else {
  66249. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  66250. }
  66251. };
  66252. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  66253. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  66254. if (dumpForDebug === void 0) { dumpForDebug = false; }
  66255. var scene = this.getScene();
  66256. if (!scene) {
  66257. return;
  66258. }
  66259. var engine = scene.getEngine();
  66260. if (this.useCameraPostProcesses !== undefined) {
  66261. useCameraPostProcess = this.useCameraPostProcesses;
  66262. }
  66263. if (this._waitingRenderList) {
  66264. this.renderList = [];
  66265. for (var index = 0; index < this._waitingRenderList.length; index++) {
  66266. var id = this._waitingRenderList[index];
  66267. var mesh_1 = scene.getMeshByID(id);
  66268. if (mesh_1) {
  66269. this.renderList.push(mesh_1);
  66270. }
  66271. }
  66272. delete this._waitingRenderList;
  66273. }
  66274. // Is predicate defined?
  66275. if (this.renderListPredicate) {
  66276. if (this.renderList) {
  66277. this.renderList.splice(0); // Clear previous renderList
  66278. }
  66279. else {
  66280. this.renderList = [];
  66281. }
  66282. var scene = this.getScene();
  66283. if (!scene) {
  66284. return;
  66285. }
  66286. var sceneMeshes = scene.meshes;
  66287. for (var index = 0; index < sceneMeshes.length; index++) {
  66288. var mesh = sceneMeshes[index];
  66289. if (this.renderListPredicate(mesh)) {
  66290. this.renderList.push(mesh);
  66291. }
  66292. }
  66293. }
  66294. this.onBeforeBindObservable.notifyObservers(this);
  66295. // Set custom projection.
  66296. // Needs to be before binding to prevent changing the aspect ratio.
  66297. var camera;
  66298. if (this.activeCamera) {
  66299. camera = this.activeCamera;
  66300. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66301. if (this.activeCamera !== scene.activeCamera) {
  66302. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  66303. }
  66304. }
  66305. else {
  66306. camera = scene.activeCamera;
  66307. if (camera) {
  66308. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66309. }
  66310. }
  66311. // Prepare renderingManager
  66312. this._renderingManager.reset();
  66313. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  66314. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  66315. var sceneRenderId = scene.getRenderId();
  66316. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  66317. var mesh = currentRenderList[meshIndex];
  66318. if (mesh) {
  66319. if (!mesh.isReady(this.refreshRate === 0)) {
  66320. this.resetRefreshCounter();
  66321. continue;
  66322. }
  66323. mesh._preActivateForIntermediateRendering(sceneRenderId);
  66324. var isMasked = void 0;
  66325. if (!this.renderList && camera) {
  66326. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  66327. }
  66328. else {
  66329. isMasked = false;
  66330. }
  66331. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  66332. mesh._activate(sceneRenderId);
  66333. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  66334. var subMesh = mesh.subMeshes[subIndex];
  66335. scene._activeIndices.addCount(subMesh.indexCount, false);
  66336. this._renderingManager.dispatch(subMesh, mesh);
  66337. }
  66338. }
  66339. }
  66340. }
  66341. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  66342. var particleSystem = scene.particleSystems[particleIndex];
  66343. var emitter = particleSystem.emitter;
  66344. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  66345. continue;
  66346. }
  66347. if (currentRenderList.indexOf(emitter) >= 0) {
  66348. this._renderingManager.dispatchParticles(particleSystem);
  66349. }
  66350. }
  66351. if (this.isCube) {
  66352. for (var face = 0; face < 6; face++) {
  66353. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66354. scene.incrementRenderId();
  66355. scene.resetCachedMaterial();
  66356. }
  66357. }
  66358. else {
  66359. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66360. }
  66361. this.onAfterUnbindObservable.notifyObservers(this);
  66362. if (scene.activeCamera) {
  66363. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  66364. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  66365. }
  66366. engine.setViewport(scene.activeCamera.viewport);
  66367. }
  66368. scene.resetCachedMaterial();
  66369. };
  66370. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  66371. var minimum = 128;
  66372. var x = renderDimension * scale;
  66373. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  66374. // Ensure we don't exceed the render dimension (while staying POT)
  66375. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  66376. };
  66377. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66378. var _this = this;
  66379. if (!this._texture) {
  66380. return;
  66381. }
  66382. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  66383. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66384. });
  66385. };
  66386. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  66387. var scene = this.getScene();
  66388. if (!scene) {
  66389. return;
  66390. }
  66391. var engine = scene.getEngine();
  66392. if (!this._texture) {
  66393. return;
  66394. }
  66395. // Bind
  66396. if (this._postProcessManager) {
  66397. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  66398. }
  66399. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  66400. if (this._texture) {
  66401. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  66402. }
  66403. }
  66404. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  66405. // Clear
  66406. if (this.onClearObservable.hasObservers()) {
  66407. this.onClearObservable.notifyObservers(engine);
  66408. }
  66409. else {
  66410. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  66411. }
  66412. if (!this._doNotChangeAspectRatio) {
  66413. scene.updateTransformMatrix(true);
  66414. }
  66415. // Render
  66416. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  66417. if (this._postProcessManager) {
  66418. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  66419. }
  66420. else if (useCameraPostProcess) {
  66421. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  66422. }
  66423. if (!this._doNotChangeAspectRatio) {
  66424. scene.updateTransformMatrix(true);
  66425. }
  66426. // Dump ?
  66427. if (dumpForDebug) {
  66428. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  66429. }
  66430. // Unbind
  66431. if (!this.isCube || faceIndex === 5) {
  66432. if (this.isCube) {
  66433. if (faceIndex === 5) {
  66434. engine.generateMipMapsForCubemap(this._texture);
  66435. }
  66436. }
  66437. this.unbindFrameBuffer(engine, faceIndex);
  66438. }
  66439. else {
  66440. this.onAfterRenderObservable.notifyObservers(faceIndex);
  66441. }
  66442. };
  66443. /**
  66444. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  66445. * This allowed control for front to back rendering or reversly depending of the special needs.
  66446. *
  66447. * @param renderingGroupId The rendering group id corresponding to its index
  66448. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  66449. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  66450. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  66451. */
  66452. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  66453. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  66454. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  66455. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  66456. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  66457. };
  66458. /**
  66459. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  66460. *
  66461. * @param renderingGroupId The rendering group id corresponding to its index
  66462. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  66463. */
  66464. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  66465. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  66466. this._renderingManager._useSceneAutoClearSetup = false;
  66467. };
  66468. RenderTargetTexture.prototype.clone = function () {
  66469. var textureSize = this.getSize();
  66470. 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);
  66471. // Base texture
  66472. newTexture.hasAlpha = this.hasAlpha;
  66473. newTexture.level = this.level;
  66474. // RenderTarget Texture
  66475. newTexture.coordinatesMode = this.coordinatesMode;
  66476. if (this.renderList) {
  66477. newTexture.renderList = this.renderList.slice(0);
  66478. }
  66479. return newTexture;
  66480. };
  66481. RenderTargetTexture.prototype.serialize = function () {
  66482. if (!this.name) {
  66483. return null;
  66484. }
  66485. var serializationObject = _super.prototype.serialize.call(this);
  66486. serializationObject.renderTargetSize = this.getRenderSize();
  66487. serializationObject.renderList = [];
  66488. if (this.renderList) {
  66489. for (var index = 0; index < this.renderList.length; index++) {
  66490. serializationObject.renderList.push(this.renderList[index].id);
  66491. }
  66492. }
  66493. return serializationObject;
  66494. };
  66495. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  66496. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  66497. var objBuffer = this.getInternalTexture();
  66498. var scene = this.getScene();
  66499. if (objBuffer && scene) {
  66500. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  66501. }
  66502. };
  66503. RenderTargetTexture.prototype.dispose = function () {
  66504. if (this._postProcessManager) {
  66505. this._postProcessManager.dispose();
  66506. this._postProcessManager = null;
  66507. }
  66508. this.clearPostProcesses(true);
  66509. if (this._resizeObserver) {
  66510. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  66511. this._resizeObserver = null;
  66512. }
  66513. this.renderList = null;
  66514. // Remove from custom render targets
  66515. var scene = this.getScene();
  66516. if (!scene) {
  66517. return;
  66518. }
  66519. var index = scene.customRenderTargets.indexOf(this);
  66520. if (index >= 0) {
  66521. scene.customRenderTargets.splice(index, 1);
  66522. }
  66523. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  66524. var camera = _a[_i];
  66525. index = camera.customRenderTargets.indexOf(this);
  66526. if (index >= 0) {
  66527. camera.customRenderTargets.splice(index, 1);
  66528. }
  66529. }
  66530. _super.prototype.dispose.call(this);
  66531. };
  66532. /** @hidden */
  66533. RenderTargetTexture.prototype._rebuild = function () {
  66534. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  66535. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  66536. }
  66537. if (this._postProcessManager) {
  66538. this._postProcessManager._rebuild();
  66539. }
  66540. };
  66541. /**
  66542. * Clear the info related to rendering groups preventing retention point in material dispose.
  66543. */
  66544. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  66545. if (this._renderingManager) {
  66546. this._renderingManager.freeRenderingGroups();
  66547. }
  66548. };
  66549. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  66550. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  66551. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  66552. return RenderTargetTexture;
  66553. }(BABYLON.Texture));
  66554. BABYLON.RenderTargetTexture = RenderTargetTexture;
  66555. })(BABYLON || (BABYLON = {}));
  66556. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  66557. var BABYLON;
  66558. (function (BABYLON) {
  66559. ;
  66560. var MultiRenderTarget = /** @class */ (function (_super) {
  66561. __extends(MultiRenderTarget, _super);
  66562. function MultiRenderTarget(name, size, count, scene, options) {
  66563. var _this = this;
  66564. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  66565. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  66566. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  66567. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  66568. _this._engine = scene.getEngine();
  66569. if (!_this.isSupported) {
  66570. _this.dispose();
  66571. return;
  66572. }
  66573. var types = [];
  66574. var samplingModes = [];
  66575. for (var i = 0; i < count; i++) {
  66576. if (options && options.types && options.types[i] !== undefined) {
  66577. types.push(options.types[i]);
  66578. }
  66579. else {
  66580. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66581. }
  66582. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  66583. samplingModes.push(options.samplingModes[i]);
  66584. }
  66585. else {
  66586. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66587. }
  66588. }
  66589. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  66590. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  66591. _this._size = size;
  66592. _this._multiRenderTargetOptions = {
  66593. samplingModes: samplingModes,
  66594. generateMipMaps: generateMipMaps,
  66595. generateDepthBuffer: generateDepthBuffer,
  66596. generateStencilBuffer: generateStencilBuffer,
  66597. generateDepthTexture: generateDepthTexture,
  66598. types: types,
  66599. textureCount: count
  66600. };
  66601. _this._createInternalTextures();
  66602. _this._createTextures();
  66603. return _this;
  66604. }
  66605. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  66606. get: function () {
  66607. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  66608. },
  66609. enumerable: true,
  66610. configurable: true
  66611. });
  66612. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  66613. get: function () {
  66614. return this._textures;
  66615. },
  66616. enumerable: true,
  66617. configurable: true
  66618. });
  66619. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  66620. get: function () {
  66621. return this._textures[this._textures.length - 1];
  66622. },
  66623. enumerable: true,
  66624. configurable: true
  66625. });
  66626. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  66627. set: function (wrap) {
  66628. if (this._textures) {
  66629. for (var i = 0; i < this._textures.length; i++) {
  66630. this._textures[i].wrapU = wrap;
  66631. }
  66632. }
  66633. },
  66634. enumerable: true,
  66635. configurable: true
  66636. });
  66637. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  66638. set: function (wrap) {
  66639. if (this._textures) {
  66640. for (var i = 0; i < this._textures.length; i++) {
  66641. this._textures[i].wrapV = wrap;
  66642. }
  66643. }
  66644. },
  66645. enumerable: true,
  66646. configurable: true
  66647. });
  66648. /** @hidden */
  66649. MultiRenderTarget.prototype._rebuild = function () {
  66650. this.releaseInternalTextures();
  66651. this._createInternalTextures();
  66652. for (var i = 0; i < this._internalTextures.length; i++) {
  66653. var texture = this._textures[i];
  66654. texture._texture = this._internalTextures[i];
  66655. }
  66656. // Keeps references to frame buffer and stencil/depth buffer
  66657. this._texture = this._internalTextures[0];
  66658. };
  66659. MultiRenderTarget.prototype._createInternalTextures = function () {
  66660. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  66661. };
  66662. MultiRenderTarget.prototype._createTextures = function () {
  66663. this._textures = [];
  66664. for (var i = 0; i < this._internalTextures.length; i++) {
  66665. var texture = new BABYLON.Texture(null, this.getScene());
  66666. texture._texture = this._internalTextures[i];
  66667. this._textures.push(texture);
  66668. }
  66669. // Keeps references to frame buffer and stencil/depth buffer
  66670. this._texture = this._internalTextures[0];
  66671. };
  66672. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  66673. get: function () {
  66674. return this._samples;
  66675. },
  66676. set: function (value) {
  66677. if (this._samples === value) {
  66678. return;
  66679. }
  66680. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  66681. },
  66682. enumerable: true,
  66683. configurable: true
  66684. });
  66685. MultiRenderTarget.prototype.resize = function (size) {
  66686. this.releaseInternalTextures();
  66687. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  66688. this._createInternalTextures();
  66689. };
  66690. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66691. var _this = this;
  66692. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  66693. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66694. });
  66695. };
  66696. MultiRenderTarget.prototype.dispose = function () {
  66697. this.releaseInternalTextures();
  66698. _super.prototype.dispose.call(this);
  66699. };
  66700. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  66701. if (!this._internalTextures) {
  66702. return;
  66703. }
  66704. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  66705. if (this._internalTextures[i] !== undefined) {
  66706. this._internalTextures[i].dispose();
  66707. this._internalTextures.splice(i, 1);
  66708. }
  66709. }
  66710. };
  66711. return MultiRenderTarget;
  66712. }(BABYLON.RenderTargetTexture));
  66713. BABYLON.MultiRenderTarget = MultiRenderTarget;
  66714. })(BABYLON || (BABYLON = {}));
  66715. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  66716. var BABYLON;
  66717. (function (BABYLON) {
  66718. var MirrorTexture = /** @class */ (function (_super) {
  66719. __extends(MirrorTexture, _super);
  66720. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  66721. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  66723. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66724. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  66725. _this.scene = scene;
  66726. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  66727. _this._transformMatrix = BABYLON.Matrix.Zero();
  66728. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  66729. _this._adaptiveBlurKernel = 0;
  66730. _this._blurKernelX = 0;
  66731. _this._blurKernelY = 0;
  66732. _this._blurRatio = 1.0;
  66733. _this.ignoreCameraViewport = true;
  66734. _this._updateGammaSpace();
  66735. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  66736. _this._updateGammaSpace;
  66737. });
  66738. _this.onBeforeRenderObservable.add(function () {
  66739. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  66740. _this._savedViewMatrix = scene.getViewMatrix();
  66741. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  66742. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  66743. scene.clipPlane = _this.mirrorPlane;
  66744. scene.getEngine().cullBackFaces = false;
  66745. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  66746. });
  66747. _this.onAfterRenderObservable.add(function () {
  66748. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  66749. scene.getEngine().cullBackFaces = true;
  66750. scene._mirroredCameraPosition = null;
  66751. delete scene.clipPlane;
  66752. });
  66753. return _this;
  66754. }
  66755. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  66756. get: function () {
  66757. return this._blurRatio;
  66758. },
  66759. set: function (value) {
  66760. if (this._blurRatio === value) {
  66761. return;
  66762. }
  66763. this._blurRatio = value;
  66764. this._preparePostProcesses();
  66765. },
  66766. enumerable: true,
  66767. configurable: true
  66768. });
  66769. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  66770. set: function (value) {
  66771. this._adaptiveBlurKernel = value;
  66772. this._autoComputeBlurKernel();
  66773. },
  66774. enumerable: true,
  66775. configurable: true
  66776. });
  66777. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  66778. set: function (value) {
  66779. this.blurKernelX = value;
  66780. this.blurKernelY = value;
  66781. },
  66782. enumerable: true,
  66783. configurable: true
  66784. });
  66785. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  66786. get: function () {
  66787. return this._blurKernelX;
  66788. },
  66789. set: function (value) {
  66790. if (this._blurKernelX === value) {
  66791. return;
  66792. }
  66793. this._blurKernelX = value;
  66794. this._preparePostProcesses();
  66795. },
  66796. enumerable: true,
  66797. configurable: true
  66798. });
  66799. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  66800. get: function () {
  66801. return this._blurKernelY;
  66802. },
  66803. set: function (value) {
  66804. if (this._blurKernelY === value) {
  66805. return;
  66806. }
  66807. this._blurKernelY = value;
  66808. this._preparePostProcesses();
  66809. },
  66810. enumerable: true,
  66811. configurable: true
  66812. });
  66813. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  66814. var engine = this.getScene().getEngine();
  66815. var dw = this.getRenderWidth() / engine.getRenderWidth();
  66816. var dh = this.getRenderHeight() / engine.getRenderHeight();
  66817. this.blurKernelX = this._adaptiveBlurKernel * dw;
  66818. this.blurKernelY = this._adaptiveBlurKernel * dh;
  66819. };
  66820. MirrorTexture.prototype._onRatioRescale = function () {
  66821. if (this._sizeRatio) {
  66822. this.resize(this._initialSizeParameter);
  66823. if (!this._adaptiveBlurKernel) {
  66824. this._preparePostProcesses();
  66825. }
  66826. }
  66827. if (this._adaptiveBlurKernel) {
  66828. this._autoComputeBlurKernel();
  66829. }
  66830. };
  66831. MirrorTexture.prototype._updateGammaSpace = function () {
  66832. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  66833. };
  66834. MirrorTexture.prototype._preparePostProcesses = function () {
  66835. this.clearPostProcesses(true);
  66836. if (this._blurKernelX && this._blurKernelY) {
  66837. var engine = this.getScene().getEngine();
  66838. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66839. 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);
  66840. this._blurX.autoClear = false;
  66841. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  66842. this._blurX.inputTexture = this._texture;
  66843. }
  66844. else {
  66845. this._blurX.alwaysForcePOT = true;
  66846. }
  66847. 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);
  66848. this._blurY.autoClear = false;
  66849. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  66850. this.addPostProcess(this._blurX);
  66851. this.addPostProcess(this._blurY);
  66852. }
  66853. else {
  66854. if (this._blurY) {
  66855. this.removePostProcess(this._blurY);
  66856. this._blurY.dispose();
  66857. this._blurY = null;
  66858. }
  66859. if (this._blurX) {
  66860. this.removePostProcess(this._blurX);
  66861. this._blurX.dispose();
  66862. this._blurX = null;
  66863. }
  66864. }
  66865. };
  66866. MirrorTexture.prototype.clone = function () {
  66867. var scene = this.getScene();
  66868. if (!scene) {
  66869. return this;
  66870. }
  66871. var textureSize = this.getSize();
  66872. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  66873. // Base texture
  66874. newTexture.hasAlpha = this.hasAlpha;
  66875. newTexture.level = this.level;
  66876. // Mirror Texture
  66877. newTexture.mirrorPlane = this.mirrorPlane.clone();
  66878. if (this.renderList) {
  66879. newTexture.renderList = this.renderList.slice(0);
  66880. }
  66881. return newTexture;
  66882. };
  66883. MirrorTexture.prototype.serialize = function () {
  66884. if (!this.name) {
  66885. return null;
  66886. }
  66887. var serializationObject = _super.prototype.serialize.call(this);
  66888. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  66889. return serializationObject;
  66890. };
  66891. MirrorTexture.prototype.dispose = function () {
  66892. _super.prototype.dispose.call(this);
  66893. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  66894. };
  66895. return MirrorTexture;
  66896. }(BABYLON.RenderTargetTexture));
  66897. BABYLON.MirrorTexture = MirrorTexture;
  66898. })(BABYLON || (BABYLON = {}));
  66899. //# sourceMappingURL=babylon.mirrorTexture.js.map
  66900. var BABYLON;
  66901. (function (BABYLON) {
  66902. /**
  66903. * Creates a refraction texture used by refraction channel of the standard material.
  66904. * @param name the texture name
  66905. * @param size size of the underlying texture
  66906. * @param scene root scene
  66907. */
  66908. var RefractionTexture = /** @class */ (function (_super) {
  66909. __extends(RefractionTexture, _super);
  66910. function RefractionTexture(name, size, scene, generateMipMaps) {
  66911. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  66912. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  66913. _this.depth = 2.0;
  66914. _this.onBeforeRenderObservable.add(function () {
  66915. scene.clipPlane = _this.refractionPlane;
  66916. });
  66917. _this.onAfterRenderObservable.add(function () {
  66918. delete scene.clipPlane;
  66919. });
  66920. return _this;
  66921. }
  66922. RefractionTexture.prototype.clone = function () {
  66923. var scene = this.getScene();
  66924. if (!scene) {
  66925. return this;
  66926. }
  66927. var textureSize = this.getSize();
  66928. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  66929. // Base texture
  66930. newTexture.hasAlpha = this.hasAlpha;
  66931. newTexture.level = this.level;
  66932. // Refraction Texture
  66933. newTexture.refractionPlane = this.refractionPlane.clone();
  66934. if (this.renderList) {
  66935. newTexture.renderList = this.renderList.slice(0);
  66936. }
  66937. newTexture.depth = this.depth;
  66938. return newTexture;
  66939. };
  66940. RefractionTexture.prototype.serialize = function () {
  66941. if (!this.name) {
  66942. return null;
  66943. }
  66944. var serializationObject = _super.prototype.serialize.call(this);
  66945. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  66946. serializationObject.depth = this.depth;
  66947. return serializationObject;
  66948. };
  66949. return RefractionTexture;
  66950. }(BABYLON.RenderTargetTexture));
  66951. BABYLON.RefractionTexture = RefractionTexture;
  66952. })(BABYLON || (BABYLON = {}));
  66953. //# sourceMappingURL=babylon.refractionTexture.js.map
  66954. var BABYLON;
  66955. (function (BABYLON) {
  66956. /**
  66957. * A class extending {BABYLON.Texture} allowing drawing on a texture
  66958. * @see http://doc.babylonjs.com/how_to/dynamictexture
  66959. */
  66960. var DynamicTexture = /** @class */ (function (_super) {
  66961. __extends(DynamicTexture, _super);
  66962. /**
  66963. * Creates a {BABYLON.DynamicTexture}
  66964. * @param name defines the name of the texture
  66965. * @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
  66966. * @param scene defines the scene where you want the texture
  66967. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  66968. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  66969. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  66970. */
  66971. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  66972. if (scene === void 0) { scene = null; }
  66973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66974. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66975. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  66976. _this.name = name;
  66977. _this._engine = _this.getScene().getEngine();
  66978. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66979. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66980. _this._generateMipMaps = generateMipMaps;
  66981. if (options.getContext) {
  66982. _this._canvas = options;
  66983. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66984. }
  66985. else {
  66986. _this._canvas = document.createElement("canvas");
  66987. if (options.width || options.width === 0) {
  66988. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66989. }
  66990. else {
  66991. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  66992. }
  66993. }
  66994. var textureSize = _this.getSize();
  66995. _this._canvas.width = textureSize.width;
  66996. _this._canvas.height = textureSize.height;
  66997. _this._context = _this._canvas.getContext("2d");
  66998. return _this;
  66999. }
  67000. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  67001. /**
  67002. * Gets the current state of canRescale
  67003. */
  67004. get: function () {
  67005. return true;
  67006. },
  67007. enumerable: true,
  67008. configurable: true
  67009. });
  67010. DynamicTexture.prototype._recreate = function (textureSize) {
  67011. this._canvas.width = textureSize.width;
  67012. this._canvas.height = textureSize.height;
  67013. this.releaseInternalTexture();
  67014. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  67015. };
  67016. /**
  67017. * Scales the texture
  67018. * @param ratio the scale factor to apply to both width and height
  67019. */
  67020. DynamicTexture.prototype.scale = function (ratio) {
  67021. var textureSize = this.getSize();
  67022. textureSize.width *= ratio;
  67023. textureSize.height *= ratio;
  67024. this._recreate(textureSize);
  67025. };
  67026. /**
  67027. * Resizes the texture
  67028. * @param width the new width
  67029. * @param height the new height
  67030. */
  67031. DynamicTexture.prototype.scaleTo = function (width, height) {
  67032. var textureSize = this.getSize();
  67033. textureSize.width = width;
  67034. textureSize.height = height;
  67035. this._recreate(textureSize);
  67036. };
  67037. /**
  67038. * Gets the context of the canvas used by the texture
  67039. * @returns the canvas context of the dynamic texture
  67040. */
  67041. DynamicTexture.prototype.getContext = function () {
  67042. return this._context;
  67043. };
  67044. /**
  67045. * Clears the texture
  67046. */
  67047. DynamicTexture.prototype.clear = function () {
  67048. var size = this.getSize();
  67049. this._context.fillRect(0, 0, size.width, size.height);
  67050. };
  67051. /**
  67052. * Updates the texture
  67053. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67054. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  67055. */
  67056. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  67057. if (premulAlpha === void 0) { premulAlpha = false; }
  67058. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  67059. };
  67060. /**
  67061. * Draws text onto the texture
  67062. * @param text defines the text to be drawn
  67063. * @param x defines the placement of the text from the left
  67064. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  67065. * @param font defines the font to be used with font-style, font-size, font-name
  67066. * @param color defines the color used for the text
  67067. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  67068. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67069. * @param update defines whether texture is immediately update (default is true)
  67070. */
  67071. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  67072. if (update === void 0) { update = true; }
  67073. var size = this.getSize();
  67074. if (clearColor) {
  67075. this._context.fillStyle = clearColor;
  67076. this._context.fillRect(0, 0, size.width, size.height);
  67077. }
  67078. this._context.font = font;
  67079. if (x === null || x === undefined) {
  67080. var textSize = this._context.measureText(text);
  67081. x = (size.width - textSize.width) / 2;
  67082. }
  67083. if (y === null || y === undefined) {
  67084. var fontSize = parseInt((font.replace(/\D/g, '')));
  67085. y = (size.height / 2) + (fontSize / 3.65);
  67086. }
  67087. this._context.fillStyle = color;
  67088. this._context.fillText(text, x, y);
  67089. if (update) {
  67090. this.update(invertY);
  67091. }
  67092. };
  67093. /**
  67094. * Clones the texture
  67095. * @returns the clone of the texture.
  67096. */
  67097. DynamicTexture.prototype.clone = function () {
  67098. var scene = this.getScene();
  67099. if (!scene) {
  67100. return this;
  67101. }
  67102. var textureSize = this.getSize();
  67103. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  67104. // Base texture
  67105. newTexture.hasAlpha = this.hasAlpha;
  67106. newTexture.level = this.level;
  67107. // Dynamic Texture
  67108. newTexture.wrapU = this.wrapU;
  67109. newTexture.wrapV = this.wrapV;
  67110. return newTexture;
  67111. };
  67112. /**
  67113. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  67114. * @returns a serialized dynamic texture object
  67115. */
  67116. DynamicTexture.prototype.serialize = function () {
  67117. var scene = this.getScene();
  67118. if (scene && !scene.isReady()) {
  67119. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  67120. }
  67121. var serializationObject = _super.prototype.serialize.call(this);
  67122. serializationObject.base64String = this._canvas.toDataURL();
  67123. serializationObject.invertY = this._invertY;
  67124. serializationObject.samplingMode = this.samplingMode;
  67125. return serializationObject;
  67126. };
  67127. /** @hidden */
  67128. DynamicTexture.prototype._rebuild = function () {
  67129. this.update();
  67130. };
  67131. return DynamicTexture;
  67132. }(BABYLON.Texture));
  67133. BABYLON.DynamicTexture = DynamicTexture;
  67134. })(BABYLON || (BABYLON = {}));
  67135. //# sourceMappingURL=babylon.dynamicTexture.js.map
  67136. var BABYLON;
  67137. (function (BABYLON) {
  67138. var VideoTexture = /** @class */ (function (_super) {
  67139. __extends(VideoTexture, _super);
  67140. /**
  67141. * Creates a video texture.
  67142. * Sample : https://doc.babylonjs.com/how_to/video_texture
  67143. * @param {string | null} name optional name, will detect from video source, if not defined
  67144. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  67145. * @param {BABYLON.Scene} scene is obviously the current scene.
  67146. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  67147. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  67148. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  67149. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  67150. */
  67151. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  67152. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67153. if (invertY === void 0) { invertY = false; }
  67154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67155. if (settings === void 0) { settings = {
  67156. autoPlay: true,
  67157. loop: true,
  67158. autoUpdateTexture: true,
  67159. }; }
  67160. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67161. _this._onUserActionRequestedObservable = null;
  67162. _this._stillImageCaptured = false;
  67163. _this._poster = false;
  67164. _this._createInternalTexture = function () {
  67165. if (_this._texture != null) {
  67166. if (_this._poster) {
  67167. _this._texture.dispose();
  67168. _this._poster = false;
  67169. }
  67170. else {
  67171. return;
  67172. }
  67173. }
  67174. if (!_this._engine.needPOTTextures ||
  67175. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  67176. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67177. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67178. }
  67179. else {
  67180. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67181. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67182. _this._generateMipMaps = false;
  67183. }
  67184. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  67185. if (!_this.video.autoplay) {
  67186. var oldHandler_1 = _this.video.onplaying;
  67187. var error_1 = false;
  67188. _this.video.onplaying = function () {
  67189. _this.video.onplaying = oldHandler_1;
  67190. _this._texture.isReady = true;
  67191. _this._updateInternalTexture();
  67192. if (!error_1) {
  67193. _this.video.pause();
  67194. }
  67195. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67196. _this.onLoadObservable.notifyObservers(_this);
  67197. }
  67198. };
  67199. var playing = _this.video.play();
  67200. if (playing) {
  67201. playing.then(function () {
  67202. // Everything is good.
  67203. })
  67204. .catch(function () {
  67205. error_1 = true;
  67206. // On Chrome for instance, new policies might prevent playing without user interaction.
  67207. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  67208. _this._onUserActionRequestedObservable.notifyObservers(_this);
  67209. }
  67210. });
  67211. }
  67212. else {
  67213. _this.video.onplaying = oldHandler_1;
  67214. _this._texture.isReady = true;
  67215. _this._updateInternalTexture();
  67216. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67217. _this.onLoadObservable.notifyObservers(_this);
  67218. }
  67219. }
  67220. }
  67221. else {
  67222. _this._texture.isReady = true;
  67223. _this._updateInternalTexture();
  67224. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67225. _this.onLoadObservable.notifyObservers(_this);
  67226. }
  67227. }
  67228. };
  67229. _this.reset = function () {
  67230. if (_this._texture == null) {
  67231. return;
  67232. }
  67233. if (!_this._poster) {
  67234. _this._texture.dispose();
  67235. _this._texture = null;
  67236. }
  67237. };
  67238. _this._updateInternalTexture = function (e) {
  67239. if (_this._texture == null || !_this._texture.isReady) {
  67240. return;
  67241. }
  67242. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  67243. return;
  67244. }
  67245. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  67246. };
  67247. _this._engine = _this.getScene().getEngine();
  67248. _this._generateMipMaps = generateMipMaps;
  67249. _this._samplingMode = samplingMode;
  67250. _this.autoUpdateTexture = settings.autoUpdateTexture;
  67251. _this.name = name || _this._getName(src);
  67252. _this.video = _this._getVideo(src);
  67253. if (settings.poster) {
  67254. _this.video.poster = settings.poster;
  67255. }
  67256. if (settings.autoPlay !== undefined) {
  67257. _this.video.autoplay = settings.autoPlay;
  67258. }
  67259. if (settings.loop !== undefined) {
  67260. _this.video.loop = settings.loop;
  67261. }
  67262. _this.video.setAttribute("playsinline", "");
  67263. _this.video.addEventListener("canplay", _this._createInternalTexture);
  67264. _this.video.addEventListener("paused", _this._updateInternalTexture);
  67265. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  67266. _this.video.addEventListener("emptied", _this.reset);
  67267. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  67268. _this._createInternalTexture();
  67269. }
  67270. if (settings.poster) {
  67271. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  67272. _this._poster = true;
  67273. }
  67274. return _this;
  67275. }
  67276. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  67277. get: function () {
  67278. if (!this._onUserActionRequestedObservable) {
  67279. this._onUserActionRequestedObservable = new BABYLON.Observable();
  67280. }
  67281. return this._onUserActionRequestedObservable;
  67282. },
  67283. enumerable: true,
  67284. configurable: true
  67285. });
  67286. VideoTexture.prototype._getName = function (src) {
  67287. if (src instanceof HTMLVideoElement) {
  67288. return src.currentSrc;
  67289. }
  67290. if (typeof src === "object") {
  67291. return src.toString();
  67292. }
  67293. return src;
  67294. };
  67295. ;
  67296. VideoTexture.prototype._getVideo = function (src) {
  67297. if (src instanceof HTMLVideoElement) {
  67298. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  67299. return src;
  67300. }
  67301. var video = document.createElement("video");
  67302. if (typeof src === "string") {
  67303. BABYLON.Tools.SetCorsBehavior(src, video);
  67304. video.src = src;
  67305. }
  67306. else {
  67307. BABYLON.Tools.SetCorsBehavior(src[0], video);
  67308. src.forEach(function (url) {
  67309. var source = document.createElement("source");
  67310. source.src = url;
  67311. video.appendChild(source);
  67312. });
  67313. }
  67314. return video;
  67315. };
  67316. ;
  67317. /**
  67318. * @hidden Internal method to initiate `update`.
  67319. */
  67320. VideoTexture.prototype._rebuild = function () {
  67321. this.update();
  67322. };
  67323. /**
  67324. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  67325. */
  67326. VideoTexture.prototype.update = function () {
  67327. if (!this.autoUpdateTexture) {
  67328. // Expecting user to call `updateTexture` manually
  67329. return;
  67330. }
  67331. this.updateTexture(true);
  67332. };
  67333. /**
  67334. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  67335. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  67336. */
  67337. VideoTexture.prototype.updateTexture = function (isVisible) {
  67338. if (!isVisible) {
  67339. return;
  67340. }
  67341. if (this.video.paused && this._stillImageCaptured) {
  67342. return;
  67343. }
  67344. this._stillImageCaptured = true;
  67345. this._updateInternalTexture();
  67346. };
  67347. /**
  67348. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  67349. * @param url New url.
  67350. */
  67351. VideoTexture.prototype.updateURL = function (url) {
  67352. this.video.src = url;
  67353. };
  67354. VideoTexture.prototype.dispose = function () {
  67355. _super.prototype.dispose.call(this);
  67356. if (this._onUserActionRequestedObservable) {
  67357. this._onUserActionRequestedObservable.clear();
  67358. this._onUserActionRequestedObservable = null;
  67359. }
  67360. this.video.removeEventListener("canplay", this._createInternalTexture);
  67361. this.video.removeEventListener("paused", this._updateInternalTexture);
  67362. this.video.removeEventListener("seeked", this._updateInternalTexture);
  67363. this.video.removeEventListener("emptied", this.reset);
  67364. this.video.pause();
  67365. };
  67366. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  67367. var video = document.createElement("video");
  67368. video.setAttribute('autoplay', '');
  67369. video.setAttribute('muted', '');
  67370. video.setAttribute('playsinline', '');
  67371. var constraintsDeviceId;
  67372. if (constraints && constraints.deviceId) {
  67373. constraintsDeviceId = {
  67374. exact: constraints.deviceId,
  67375. };
  67376. }
  67377. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  67378. if (navigator.mediaDevices) {
  67379. navigator.mediaDevices.getUserMedia({ video: constraints })
  67380. .then(function (stream) {
  67381. if (video.mozSrcObject !== undefined) {
  67382. // hack for Firefox < 19
  67383. video.mozSrcObject = stream;
  67384. }
  67385. else {
  67386. video.srcObject = stream;
  67387. }
  67388. var onPlaying = function () {
  67389. if (onReady) {
  67390. onReady(new VideoTexture("video", video, scene, true, true));
  67391. }
  67392. video.removeEventListener("playing", onPlaying);
  67393. };
  67394. video.addEventListener("playing", onPlaying);
  67395. video.play();
  67396. })
  67397. .catch(function (err) {
  67398. BABYLON.Tools.Error(err.name);
  67399. });
  67400. }
  67401. else {
  67402. navigator.getUserMedia =
  67403. navigator.getUserMedia ||
  67404. navigator.webkitGetUserMedia ||
  67405. navigator.mozGetUserMedia ||
  67406. navigator.msGetUserMedia;
  67407. if (navigator.getUserMedia) {
  67408. navigator.getUserMedia({
  67409. video: {
  67410. deviceId: constraintsDeviceId,
  67411. width: {
  67412. min: (constraints && constraints.minWidth) || 256,
  67413. max: (constraints && constraints.maxWidth) || 640,
  67414. },
  67415. height: {
  67416. min: (constraints && constraints.minHeight) || 256,
  67417. max: (constraints && constraints.maxHeight) || 480,
  67418. },
  67419. },
  67420. }, function (stream) {
  67421. if (video.mozSrcObject !== undefined) {
  67422. // hack for Firefox < 19
  67423. video.mozSrcObject = stream;
  67424. }
  67425. else {
  67426. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  67427. }
  67428. video.play();
  67429. if (onReady) {
  67430. onReady(new VideoTexture("video", video, scene, true, true));
  67431. }
  67432. }, function (e) {
  67433. BABYLON.Tools.Error(e.name);
  67434. });
  67435. }
  67436. }
  67437. };
  67438. return VideoTexture;
  67439. }(BABYLON.Texture));
  67440. BABYLON.VideoTexture = VideoTexture;
  67441. })(BABYLON || (BABYLON = {}));
  67442. //# sourceMappingURL=babylon.videoTexture.js.map
  67443. var BABYLON;
  67444. (function (BABYLON) {
  67445. var RawTexture = /** @class */ (function (_super) {
  67446. __extends(RawTexture, _super);
  67447. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  67448. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67449. if (invertY === void 0) { invertY = false; }
  67450. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67451. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67452. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67453. _this.format = format;
  67454. _this._engine = scene.getEngine();
  67455. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  67456. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67457. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67458. return _this;
  67459. }
  67460. RawTexture.prototype.update = function (data) {
  67461. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67462. };
  67463. // Statics
  67464. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67465. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67466. if (invertY === void 0) { invertY = false; }
  67467. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67468. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  67469. };
  67470. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67471. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67472. if (invertY === void 0) { invertY = false; }
  67473. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67474. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67475. };
  67476. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67477. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67478. if (invertY === void 0) { invertY = false; }
  67479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67480. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67481. };
  67482. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67483. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67484. if (invertY === void 0) { invertY = false; }
  67485. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67486. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67487. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  67488. };
  67489. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67490. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67491. if (invertY === void 0) { invertY = false; }
  67492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67493. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67494. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  67495. };
  67496. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67497. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67498. if (invertY === void 0) { invertY = false; }
  67499. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67500. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67501. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  67502. };
  67503. return RawTexture;
  67504. }(BABYLON.Texture));
  67505. BABYLON.RawTexture = RawTexture;
  67506. })(BABYLON || (BABYLON = {}));
  67507. //# sourceMappingURL=babylon.rawTexture.js.map
  67508. var BABYLON;
  67509. (function (BABYLON) {
  67510. /**
  67511. * Class used to store 3D textures containing user data
  67512. */
  67513. var RawTexture3D = /** @class */ (function (_super) {
  67514. __extends(RawTexture3D, _super);
  67515. /**
  67516. * Create a new RawTexture3D
  67517. * @param data defines the data of the texture
  67518. * @param width defines the width of the texture
  67519. * @param height defines the height of the texture
  67520. * @param depth defines the depth of the texture
  67521. * @param format defines the texture format to use
  67522. * @param scene defines the hosting scene
  67523. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  67524. * @param invertY defines if texture must be stored with Y axis inverted
  67525. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  67526. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  67527. */
  67528. function RawTexture3D(data, width, height, depth,
  67529. /** Gets or sets the texture format to use */
  67530. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  67531. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67532. if (invertY === void 0) { invertY = false; }
  67533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67534. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67535. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67536. _this.format = format;
  67537. _this._engine = scene.getEngine();
  67538. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  67539. _this.is3D = true;
  67540. return _this;
  67541. }
  67542. /**
  67543. * Update the texture with new data
  67544. * @param data defines the data to store in the texture
  67545. */
  67546. RawTexture3D.prototype.update = function (data) {
  67547. if (!this._texture) {
  67548. return;
  67549. }
  67550. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67551. };
  67552. return RawTexture3D;
  67553. }(BABYLON.Texture));
  67554. BABYLON.RawTexture3D = RawTexture3D;
  67555. })(BABYLON || (BABYLON = {}));
  67556. //# sourceMappingURL=babylon.rawTexture3D.js.map
  67557. var BABYLON;
  67558. (function (BABYLON) {
  67559. /**
  67560. * PostProcessManager is used to manage one or more post processes or post process pipelines
  67561. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67562. */
  67563. var PostProcessManager = /** @class */ (function () {
  67564. /**
  67565. * Creates a new instance PostProcess
  67566. * @param scene The scene that the post process is associated with.
  67567. */
  67568. function PostProcessManager(scene) {
  67569. this._vertexBuffers = {};
  67570. this._scene = scene;
  67571. }
  67572. PostProcessManager.prototype._prepareBuffers = function () {
  67573. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  67574. return;
  67575. }
  67576. // VBO
  67577. var vertices = [];
  67578. vertices.push(1, 1);
  67579. vertices.push(-1, 1);
  67580. vertices.push(-1, -1);
  67581. vertices.push(1, -1);
  67582. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67583. this._buildIndexBuffer();
  67584. };
  67585. PostProcessManager.prototype._buildIndexBuffer = function () {
  67586. // Indices
  67587. var indices = [];
  67588. indices.push(0);
  67589. indices.push(1);
  67590. indices.push(2);
  67591. indices.push(0);
  67592. indices.push(2);
  67593. indices.push(3);
  67594. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  67595. };
  67596. /**
  67597. * Rebuilds the vertex buffers of the manager.
  67598. * @hidden
  67599. */
  67600. PostProcessManager.prototype._rebuild = function () {
  67601. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67602. if (!vb) {
  67603. return;
  67604. }
  67605. vb._rebuild();
  67606. this._buildIndexBuffer();
  67607. };
  67608. // Methods
  67609. /**
  67610. * Prepares a frame to be run through a post process.
  67611. * @param sourceTexture The input texture to the post procesess. (default: null)
  67612. * @param postProcesses An array of post processes to be run. (default: null)
  67613. * @returns True if the post processes were able to be run.
  67614. * @hidden
  67615. */
  67616. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  67617. if (sourceTexture === void 0) { sourceTexture = null; }
  67618. if (postProcesses === void 0) { postProcesses = null; }
  67619. var camera = this._scene.activeCamera;
  67620. if (!camera) {
  67621. return false;
  67622. }
  67623. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67624. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67625. return false;
  67626. }
  67627. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  67628. return true;
  67629. };
  67630. /**
  67631. * Manually render a set of post processes to a texture.
  67632. * @param postProcesses An array of post processes to be run.
  67633. * @param targetTexture The target texture to render to.
  67634. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  67635. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  67636. * @param lodLevel defines which lod of the texture to render to
  67637. */
  67638. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  67639. if (targetTexture === void 0) { targetTexture = null; }
  67640. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67641. if (faceIndex === void 0) { faceIndex = 0; }
  67642. if (lodLevel === void 0) { lodLevel = 0; }
  67643. var engine = this._scene.getEngine();
  67644. for (var index = 0; index < postProcesses.length; index++) {
  67645. if (index < postProcesses.length - 1) {
  67646. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  67647. }
  67648. else {
  67649. if (targetTexture) {
  67650. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  67651. }
  67652. else {
  67653. engine.restoreDefaultFramebuffer();
  67654. }
  67655. }
  67656. var pp = postProcesses[index];
  67657. var effect = pp.apply();
  67658. if (effect) {
  67659. pp.onBeforeRenderObservable.notifyObservers(effect);
  67660. // VBOs
  67661. this._prepareBuffers();
  67662. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67663. // Draw order
  67664. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67665. pp.onAfterRenderObservable.notifyObservers(effect);
  67666. }
  67667. }
  67668. // Restore depth buffer
  67669. engine.setDepthBuffer(true);
  67670. engine.setDepthWrite(true);
  67671. };
  67672. /**
  67673. * Finalize the result of the output of the postprocesses.
  67674. * @param doNotPresent If true the result will not be displayed to the screen.
  67675. * @param targetTexture The target texture to render to.
  67676. * @param faceIndex The index of the face to bind the target texture to.
  67677. * @param postProcesses The array of post processes to render.
  67678. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  67679. * @hidden
  67680. */
  67681. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  67682. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67683. var camera = this._scene.activeCamera;
  67684. if (!camera) {
  67685. return;
  67686. }
  67687. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67688. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67689. return;
  67690. }
  67691. var engine = this._scene.getEngine();
  67692. for (var index = 0, len = postProcesses.length; index < len; index++) {
  67693. var pp = postProcesses[index];
  67694. if (index < len - 1) {
  67695. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  67696. }
  67697. else {
  67698. if (targetTexture) {
  67699. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  67700. pp._outputTexture = targetTexture;
  67701. }
  67702. else {
  67703. engine.restoreDefaultFramebuffer();
  67704. pp._outputTexture = null;
  67705. }
  67706. }
  67707. if (doNotPresent) {
  67708. break;
  67709. }
  67710. var effect = pp.apply();
  67711. if (effect) {
  67712. pp.onBeforeRenderObservable.notifyObservers(effect);
  67713. // VBOs
  67714. this._prepareBuffers();
  67715. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67716. // Draw order
  67717. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67718. pp.onAfterRenderObservable.notifyObservers(effect);
  67719. }
  67720. }
  67721. // Restore states
  67722. engine.setDepthBuffer(true);
  67723. engine.setDepthWrite(true);
  67724. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67725. };
  67726. /**
  67727. * Disposes of the post process manager.
  67728. */
  67729. PostProcessManager.prototype.dispose = function () {
  67730. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67731. if (buffer) {
  67732. buffer.dispose();
  67733. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67734. }
  67735. if (this._indexBuffer) {
  67736. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67737. this._indexBuffer = null;
  67738. }
  67739. };
  67740. return PostProcessManager;
  67741. }());
  67742. BABYLON.PostProcessManager = PostProcessManager;
  67743. })(BABYLON || (BABYLON = {}));
  67744. //# sourceMappingURL=babylon.postProcessManager.js.map
  67745. var BABYLON;
  67746. (function (BABYLON) {
  67747. /**
  67748. * PostProcess can be used to apply a shader to a texture after it has been rendered
  67749. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67750. */
  67751. var PostProcess = /** @class */ (function () {
  67752. /**
  67753. * Creates a new instance PostProcess
  67754. * @param name The name of the PostProcess.
  67755. * @param fragmentUrl The url of the fragment shader to be used.
  67756. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  67757. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  67758. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  67759. * @param camera The camera to apply the render pass to.
  67760. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67761. * @param engine The engine which the post process will be applied. (default: current engine)
  67762. * @param reusable If the post process can be reused on the same frame. (default: false)
  67763. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  67764. * @param textureType Type of textures used when performing the post process. (default: 0)
  67765. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  67766. * @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
  67767. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  67768. */
  67769. function PostProcess(
  67770. /** Name of the PostProcess. */
  67771. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  67772. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  67773. if (defines === void 0) { defines = null; }
  67774. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67775. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  67776. if (blockCompilation === void 0) { blockCompilation = false; }
  67777. this.name = name;
  67778. /**
  67779. * Width of the texture to apply the post process on
  67780. */
  67781. this.width = -1;
  67782. /**
  67783. * Height of the texture to apply the post process on
  67784. */
  67785. this.height = -1;
  67786. /**
  67787. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  67788. * @hidden
  67789. */
  67790. this._outputTexture = null;
  67791. /**
  67792. * If the buffer needs to be cleared before applying the post process. (default: true)
  67793. * Should be set to false if shader will overwrite all previous pixels.
  67794. */
  67795. this.autoClear = true;
  67796. /**
  67797. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  67798. */
  67799. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  67800. /**
  67801. * Animations to be used for the post processing
  67802. */
  67803. this.animations = new Array();
  67804. /**
  67805. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  67806. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  67807. */
  67808. this.enablePixelPerfectMode = false;
  67809. /**
  67810. * Force the postprocess to be applied without taking in account viewport
  67811. */
  67812. this.forceFullscreenViewport = true;
  67813. /**
  67814. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  67815. *
  67816. * | Value | Type | Description |
  67817. * | ----- | ----------------------------------- | ----------- |
  67818. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  67819. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  67820. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  67821. *
  67822. */
  67823. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  67824. /**
  67825. * Force textures to be a power of two (default: false)
  67826. */
  67827. this.alwaysForcePOT = false;
  67828. /**
  67829. * Number of sample textures (default: 1)
  67830. */
  67831. this.samples = 1;
  67832. /**
  67833. * Modify the scale of the post process to be the same as the viewport (default: false)
  67834. */
  67835. this.adaptScaleToCurrentViewport = false;
  67836. this._reusable = false;
  67837. /**
  67838. * Smart array of input and output textures for the post process.
  67839. * @hidden
  67840. */
  67841. this._textures = new BABYLON.SmartArray(2);
  67842. /**
  67843. * The index in _textures that corresponds to the output texture.
  67844. * @hidden
  67845. */
  67846. this._currentRenderTextureInd = 0;
  67847. this._scaleRatio = new BABYLON.Vector2(1, 1);
  67848. this._texelSize = BABYLON.Vector2.Zero();
  67849. // Events
  67850. /**
  67851. * An event triggered when the postprocess is activated.
  67852. */
  67853. this.onActivateObservable = new BABYLON.Observable();
  67854. /**
  67855. * An event triggered when the postprocess changes its size.
  67856. */
  67857. this.onSizeChangedObservable = new BABYLON.Observable();
  67858. /**
  67859. * An event triggered when the postprocess applies its effect.
  67860. */
  67861. this.onApplyObservable = new BABYLON.Observable();
  67862. /**
  67863. * An event triggered before rendering the postprocess
  67864. */
  67865. this.onBeforeRenderObservable = new BABYLON.Observable();
  67866. /**
  67867. * An event triggered after rendering the postprocess
  67868. */
  67869. this.onAfterRenderObservable = new BABYLON.Observable();
  67870. if (camera != null) {
  67871. this._camera = camera;
  67872. this._scene = camera.getScene();
  67873. camera.attachPostProcess(this);
  67874. this._engine = this._scene.getEngine();
  67875. this._scene.postProcesses.push(this);
  67876. }
  67877. else if (engine) {
  67878. this._engine = engine;
  67879. this._engine.postProcesses.push(this);
  67880. }
  67881. this._options = options;
  67882. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  67883. this._reusable = reusable || false;
  67884. this._textureType = textureType;
  67885. this._samplers = samplers || [];
  67886. this._samplers.push("textureSampler");
  67887. this._fragmentUrl = fragmentUrl;
  67888. this._vertexUrl = vertexUrl;
  67889. this._parameters = parameters || [];
  67890. this._parameters.push("scale");
  67891. this._indexParameters = indexParameters;
  67892. if (!blockCompilation) {
  67893. this.updateEffect(defines);
  67894. }
  67895. }
  67896. Object.defineProperty(PostProcess.prototype, "onActivate", {
  67897. /**
  67898. * A function that is added to the onActivateObservable
  67899. */
  67900. set: function (callback) {
  67901. if (this._onActivateObserver) {
  67902. this.onActivateObservable.remove(this._onActivateObserver);
  67903. }
  67904. if (callback) {
  67905. this._onActivateObserver = this.onActivateObservable.add(callback);
  67906. }
  67907. },
  67908. enumerable: true,
  67909. configurable: true
  67910. });
  67911. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  67912. /**
  67913. * A function that is added to the onSizeChangedObservable
  67914. */
  67915. set: function (callback) {
  67916. if (this._onSizeChangedObserver) {
  67917. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  67918. }
  67919. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  67920. },
  67921. enumerable: true,
  67922. configurable: true
  67923. });
  67924. Object.defineProperty(PostProcess.prototype, "onApply", {
  67925. /**
  67926. * A function that is added to the onApplyObservable
  67927. */
  67928. set: function (callback) {
  67929. if (this._onApplyObserver) {
  67930. this.onApplyObservable.remove(this._onApplyObserver);
  67931. }
  67932. this._onApplyObserver = this.onApplyObservable.add(callback);
  67933. },
  67934. enumerable: true,
  67935. configurable: true
  67936. });
  67937. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  67938. /**
  67939. * A function that is added to the onBeforeRenderObservable
  67940. */
  67941. set: function (callback) {
  67942. if (this._onBeforeRenderObserver) {
  67943. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67944. }
  67945. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67946. },
  67947. enumerable: true,
  67948. configurable: true
  67949. });
  67950. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  67951. /**
  67952. * A function that is added to the onAfterRenderObservable
  67953. */
  67954. set: function (callback) {
  67955. if (this._onAfterRenderObserver) {
  67956. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67957. }
  67958. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67959. },
  67960. enumerable: true,
  67961. configurable: true
  67962. });
  67963. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  67964. /**
  67965. * 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
  67966. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  67967. */
  67968. get: function () {
  67969. return this._textures.data[this._currentRenderTextureInd];
  67970. },
  67971. set: function (value) {
  67972. this._forcedOutputTexture = value;
  67973. },
  67974. enumerable: true,
  67975. configurable: true
  67976. });
  67977. /**
  67978. * Gets the camera which post process is applied to.
  67979. * @returns The camera the post process is applied to.
  67980. */
  67981. PostProcess.prototype.getCamera = function () {
  67982. return this._camera;
  67983. };
  67984. Object.defineProperty(PostProcess.prototype, "texelSize", {
  67985. /**
  67986. * Gets the texel size of the postprocess.
  67987. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  67988. */
  67989. get: function () {
  67990. if (this._shareOutputWithPostProcess) {
  67991. return this._shareOutputWithPostProcess.texelSize;
  67992. }
  67993. if (this._forcedOutputTexture) {
  67994. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  67995. }
  67996. return this._texelSize;
  67997. },
  67998. enumerable: true,
  67999. configurable: true
  68000. });
  68001. /**
  68002. * Gets the engine which this post process belongs to.
  68003. * @returns The engine the post process was enabled with.
  68004. */
  68005. PostProcess.prototype.getEngine = function () {
  68006. return this._engine;
  68007. };
  68008. /**
  68009. * The effect that is created when initializing the post process.
  68010. * @returns The created effect corrisponding the the postprocess.
  68011. */
  68012. PostProcess.prototype.getEffect = function () {
  68013. return this._effect;
  68014. };
  68015. /**
  68016. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  68017. * @param postProcess The post process to share the output with.
  68018. * @returns This post process.
  68019. */
  68020. PostProcess.prototype.shareOutputWith = function (postProcess) {
  68021. this._disposeTextures();
  68022. this._shareOutputWithPostProcess = postProcess;
  68023. return this;
  68024. };
  68025. /**
  68026. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  68027. * This should be called if the post process that shares output with this post process is disabled/disposed.
  68028. */
  68029. PostProcess.prototype.useOwnOutput = function () {
  68030. if (this._textures.length == 0) {
  68031. this._textures = new BABYLON.SmartArray(2);
  68032. }
  68033. this._shareOutputWithPostProcess = null;
  68034. };
  68035. /**
  68036. * Updates the effect with the current post process compile time values and recompiles the shader.
  68037. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68038. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68039. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68040. * @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
  68041. * @param onCompiled Called when the shader has been compiled.
  68042. * @param onError Called if there is an error when compiling a shader.
  68043. */
  68044. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68045. if (defines === void 0) { defines = null; }
  68046. if (uniforms === void 0) { uniforms = null; }
  68047. if (samplers === void 0) { samplers = null; }
  68048. 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);
  68049. };
  68050. /**
  68051. * The post process is reusable if it can be used multiple times within one frame.
  68052. * @returns If the post process is reusable
  68053. */
  68054. PostProcess.prototype.isReusable = function () {
  68055. return this._reusable;
  68056. };
  68057. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  68058. PostProcess.prototype.markTextureDirty = function () {
  68059. this.width = -1;
  68060. };
  68061. /**
  68062. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  68063. * 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.
  68064. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  68065. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  68066. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  68067. * @returns The target texture that was bound to be written to.
  68068. */
  68069. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  68070. var _this = this;
  68071. if (sourceTexture === void 0) { sourceTexture = null; }
  68072. camera = camera || this._camera;
  68073. var scene = camera.getScene();
  68074. var engine = scene.getEngine();
  68075. var maxSize = engine.getCaps().maxTextureSize;
  68076. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  68077. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  68078. // 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
  68079. var webVRCamera = camera.parent;
  68080. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  68081. requiredWidth /= 2;
  68082. }
  68083. var desiredWidth = (this._options.width || requiredWidth);
  68084. var desiredHeight = this._options.height || requiredHeight;
  68085. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  68086. if (this.adaptScaleToCurrentViewport) {
  68087. var currentViewport = engine.currentViewport;
  68088. if (currentViewport) {
  68089. desiredWidth *= currentViewport.width;
  68090. desiredHeight *= currentViewport.height;
  68091. }
  68092. }
  68093. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  68094. if (!this._options.width) {
  68095. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  68096. }
  68097. if (!this._options.height) {
  68098. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  68099. }
  68100. }
  68101. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  68102. if (this._textures.length > 0) {
  68103. for (var i = 0; i < this._textures.length; i++) {
  68104. this._engine._releaseTexture(this._textures.data[i]);
  68105. }
  68106. this._textures.reset();
  68107. }
  68108. this.width = desiredWidth;
  68109. this.height = desiredHeight;
  68110. var textureSize = { width: this.width, height: this.height };
  68111. var textureOptions = {
  68112. generateMipMaps: false,
  68113. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  68114. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  68115. samplingMode: this.renderTargetSamplingMode,
  68116. type: this._textureType
  68117. };
  68118. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68119. if (this._reusable) {
  68120. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68121. }
  68122. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  68123. this.onSizeChangedObservable.notifyObservers(this);
  68124. }
  68125. this._textures.forEach(function (texture) {
  68126. if (texture.samples !== _this.samples) {
  68127. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  68128. }
  68129. });
  68130. }
  68131. var target;
  68132. if (this._shareOutputWithPostProcess) {
  68133. target = this._shareOutputWithPostProcess.inputTexture;
  68134. }
  68135. else if (this._forcedOutputTexture) {
  68136. target = this._forcedOutputTexture;
  68137. this.width = this._forcedOutputTexture.width;
  68138. this.height = this._forcedOutputTexture.height;
  68139. }
  68140. else {
  68141. target = this.inputTexture;
  68142. }
  68143. // Bind the input of this post process to be used as the output of the previous post process.
  68144. if (this.enablePixelPerfectMode) {
  68145. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  68146. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  68147. }
  68148. else {
  68149. this._scaleRatio.copyFromFloats(1, 1);
  68150. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  68151. }
  68152. this.onActivateObservable.notifyObservers(camera);
  68153. // Clear
  68154. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  68155. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  68156. }
  68157. if (this._reusable) {
  68158. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  68159. }
  68160. return target;
  68161. };
  68162. Object.defineProperty(PostProcess.prototype, "isSupported", {
  68163. /**
  68164. * If the post process is supported.
  68165. */
  68166. get: function () {
  68167. return this._effect.isSupported;
  68168. },
  68169. enumerable: true,
  68170. configurable: true
  68171. });
  68172. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  68173. /**
  68174. * The aspect ratio of the output texture.
  68175. */
  68176. get: function () {
  68177. if (this._shareOutputWithPostProcess) {
  68178. return this._shareOutputWithPostProcess.aspectRatio;
  68179. }
  68180. if (this._forcedOutputTexture) {
  68181. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  68182. }
  68183. return this.width / this.height;
  68184. },
  68185. enumerable: true,
  68186. configurable: true
  68187. });
  68188. /**
  68189. * Get a value indicating if the post-process is ready to be used
  68190. * @returns true if the post-process is ready (shader is compiled)
  68191. */
  68192. PostProcess.prototype.isReady = function () {
  68193. return this._effect && this._effect.isReady();
  68194. };
  68195. /**
  68196. * Binds all textures and uniforms to the shader, this will be run on every pass.
  68197. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  68198. */
  68199. PostProcess.prototype.apply = function () {
  68200. // Check
  68201. if (!this._effect || !this._effect.isReady())
  68202. return null;
  68203. // States
  68204. this._engine.enableEffect(this._effect);
  68205. this._engine.setState(false);
  68206. this._engine.setDepthBuffer(false);
  68207. this._engine.setDepthWrite(false);
  68208. // Alpha
  68209. this._engine.setAlphaMode(this.alphaMode);
  68210. if (this.alphaConstants) {
  68211. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  68212. }
  68213. // Bind the output texture of the preivous post process as the input to this post process.
  68214. var source;
  68215. if (this._shareOutputWithPostProcess) {
  68216. source = this._shareOutputWithPostProcess.inputTexture;
  68217. }
  68218. else if (this._forcedOutputTexture) {
  68219. source = this._forcedOutputTexture;
  68220. }
  68221. else {
  68222. source = this.inputTexture;
  68223. }
  68224. this._effect._bindTexture("textureSampler", source);
  68225. // Parameters
  68226. this._effect.setVector2("scale", this._scaleRatio);
  68227. this.onApplyObservable.notifyObservers(this._effect);
  68228. return this._effect;
  68229. };
  68230. PostProcess.prototype._disposeTextures = function () {
  68231. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  68232. return;
  68233. }
  68234. if (this._textures.length > 0) {
  68235. for (var i = 0; i < this._textures.length; i++) {
  68236. this._engine._releaseTexture(this._textures.data[i]);
  68237. }
  68238. }
  68239. this._textures.dispose();
  68240. };
  68241. /**
  68242. * Disposes the post process.
  68243. * @param camera The camera to dispose the post process on.
  68244. */
  68245. PostProcess.prototype.dispose = function (camera) {
  68246. camera = camera || this._camera;
  68247. this._disposeTextures();
  68248. if (this._scene) {
  68249. var index_1 = this._scene.postProcesses.indexOf(this);
  68250. if (index_1 !== -1) {
  68251. this._scene.postProcesses.splice(index_1, 1);
  68252. }
  68253. }
  68254. else {
  68255. var index_2 = this._engine.postProcesses.indexOf(this);
  68256. if (index_2 !== -1) {
  68257. this._engine.postProcesses.splice(index_2, 1);
  68258. }
  68259. }
  68260. if (!camera) {
  68261. return;
  68262. }
  68263. camera.detachPostProcess(this);
  68264. var index = camera._postProcesses.indexOf(this);
  68265. if (index === 0 && camera._postProcesses.length > 0) {
  68266. var firstPostProcess = this._camera._getFirstPostProcess();
  68267. if (firstPostProcess) {
  68268. firstPostProcess.markTextureDirty();
  68269. }
  68270. }
  68271. this.onActivateObservable.clear();
  68272. this.onAfterRenderObservable.clear();
  68273. this.onApplyObservable.clear();
  68274. this.onBeforeRenderObservable.clear();
  68275. this.onSizeChangedObservable.clear();
  68276. };
  68277. return PostProcess;
  68278. }());
  68279. BABYLON.PostProcess = PostProcess;
  68280. })(BABYLON || (BABYLON = {}));
  68281. //# sourceMappingURL=babylon.postProcess.js.map
  68282. var BABYLON;
  68283. (function (BABYLON) {
  68284. var PassPostProcess = /** @class */ (function (_super) {
  68285. __extends(PassPostProcess, _super);
  68286. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68287. if (camera === void 0) { camera = null; }
  68288. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68289. if (blockCompilation === void 0) { blockCompilation = false; }
  68290. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  68291. }
  68292. return PassPostProcess;
  68293. }(BABYLON.PostProcess));
  68294. BABYLON.PassPostProcess = PassPostProcess;
  68295. })(BABYLON || (BABYLON = {}));
  68296. //# sourceMappingURL=babylon.passPostProcess.js.map
  68297. var __assign = (this && this.__assign) || Object.assign || function(t) {
  68298. for (var s, i = 1, n = arguments.length; i < n; i++) {
  68299. s = arguments[i];
  68300. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  68301. t[p] = s[p];
  68302. }
  68303. return t;
  68304. };
  68305. var BABYLON;
  68306. (function (BABYLON) {
  68307. /**
  68308. * Default implementation IShadowGenerator.
  68309. * This is the main object responsible of generating shadows in the framework.
  68310. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  68311. */
  68312. var ShadowGenerator = /** @class */ (function () {
  68313. /**
  68314. * Creates a ShadowGenerator object.
  68315. * A ShadowGenerator is the required tool to use the shadows.
  68316. * Each light casting shadows needs to use its own ShadowGenerator.
  68317. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  68318. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  68319. * @param light The light object generating the shadows.
  68320. * @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.
  68321. */
  68322. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  68323. this._bias = 0.00005;
  68324. this._normalBias = 0;
  68325. this._blurBoxOffset = 1;
  68326. this._blurScale = 2;
  68327. this._blurKernel = 1;
  68328. this._useKernelBlur = false;
  68329. this._filter = ShadowGenerator.FILTER_NONE;
  68330. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  68331. this._contactHardeningLightSizeUVRatio = 0.1;
  68332. this._darkness = 0;
  68333. this._transparencyShadow = false;
  68334. /**
  68335. * Controls the extent to which the shadows fade out at the edge of the frustum
  68336. * Used only by directionals and spots
  68337. */
  68338. this.frustumEdgeFalloff = 0;
  68339. /**
  68340. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  68341. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  68342. * It might on the other hand introduce peter panning.
  68343. */
  68344. this.forceBackFacesOnly = false;
  68345. this._lightDirection = BABYLON.Vector3.Zero();
  68346. this._viewMatrix = BABYLON.Matrix.Zero();
  68347. this._projectionMatrix = BABYLON.Matrix.Zero();
  68348. this._transformMatrix = BABYLON.Matrix.Zero();
  68349. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68350. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68351. this._currentFaceIndex = 0;
  68352. this._currentFaceIndexCache = 0;
  68353. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  68354. this._mapSize = mapSize;
  68355. this._light = light;
  68356. this._scene = light.getScene();
  68357. light._shadowGenerator = this;
  68358. // Texture type fallback from float to int if not supported.
  68359. var caps = this._scene.getEngine().getCaps();
  68360. if (!useFullFloatFirst) {
  68361. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68362. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68363. }
  68364. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68365. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68366. }
  68367. else {
  68368. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68369. }
  68370. }
  68371. else {
  68372. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68373. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68374. }
  68375. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68376. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68377. }
  68378. else {
  68379. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68380. }
  68381. }
  68382. this._initializeGenerator();
  68383. this._applyFilterValues();
  68384. }
  68385. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  68386. /**
  68387. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  68388. */
  68389. get: function () {
  68390. return this._bias;
  68391. },
  68392. /**
  68393. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  68394. */
  68395. set: function (bias) {
  68396. this._bias = bias;
  68397. },
  68398. enumerable: true,
  68399. configurable: true
  68400. });
  68401. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  68402. /**
  68403. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68404. */
  68405. get: function () {
  68406. return this._normalBias;
  68407. },
  68408. /**
  68409. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68410. */
  68411. set: function (normalBias) {
  68412. this._normalBias = normalBias;
  68413. },
  68414. enumerable: true,
  68415. configurable: true
  68416. });
  68417. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  68418. /**
  68419. * Gets the blur box offset: offset applied during the blur pass.
  68420. * Only usefull if useKernelBlur = false
  68421. */
  68422. get: function () {
  68423. return this._blurBoxOffset;
  68424. },
  68425. /**
  68426. * Sets the blur box offset: offset applied during the blur pass.
  68427. * Only usefull if useKernelBlur = false
  68428. */
  68429. set: function (value) {
  68430. if (this._blurBoxOffset === value) {
  68431. return;
  68432. }
  68433. this._blurBoxOffset = value;
  68434. this._disposeBlurPostProcesses();
  68435. },
  68436. enumerable: true,
  68437. configurable: true
  68438. });
  68439. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  68440. /**
  68441. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  68442. * 2 means half of the size.
  68443. */
  68444. get: function () {
  68445. return this._blurScale;
  68446. },
  68447. /**
  68448. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  68449. * 2 means half of the size.
  68450. */
  68451. set: function (value) {
  68452. if (this._blurScale === value) {
  68453. return;
  68454. }
  68455. this._blurScale = value;
  68456. this._disposeBlurPostProcesses();
  68457. },
  68458. enumerable: true,
  68459. configurable: true
  68460. });
  68461. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  68462. /**
  68463. * Gets the blur kernel: kernel size of the blur pass.
  68464. * Only usefull if useKernelBlur = true
  68465. */
  68466. get: function () {
  68467. return this._blurKernel;
  68468. },
  68469. /**
  68470. * Sets the blur kernel: kernel size of the blur pass.
  68471. * Only usefull if useKernelBlur = true
  68472. */
  68473. set: function (value) {
  68474. if (this._blurKernel === value) {
  68475. return;
  68476. }
  68477. this._blurKernel = value;
  68478. this._disposeBlurPostProcesses();
  68479. },
  68480. enumerable: true,
  68481. configurable: true
  68482. });
  68483. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  68484. /**
  68485. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  68486. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68487. */
  68488. get: function () {
  68489. return this._useKernelBlur;
  68490. },
  68491. /**
  68492. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  68493. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68494. */
  68495. set: function (value) {
  68496. if (this._useKernelBlur === value) {
  68497. return;
  68498. }
  68499. this._useKernelBlur = value;
  68500. this._disposeBlurPostProcesses();
  68501. },
  68502. enumerable: true,
  68503. configurable: true
  68504. });
  68505. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  68506. /**
  68507. * Gets the depth scale used in ESM mode.
  68508. */
  68509. get: function () {
  68510. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  68511. },
  68512. /**
  68513. * Sets the depth scale used in ESM mode.
  68514. * This can override the scale stored on the light.
  68515. */
  68516. set: function (value) {
  68517. this._depthScale = value;
  68518. },
  68519. enumerable: true,
  68520. configurable: true
  68521. });
  68522. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  68523. /**
  68524. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  68525. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68526. */
  68527. get: function () {
  68528. return this._filter;
  68529. },
  68530. /**
  68531. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  68532. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68533. */
  68534. set: function (value) {
  68535. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  68536. if (this._light.needCube()) {
  68537. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68538. this.useExponentialShadowMap = true;
  68539. return;
  68540. }
  68541. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68542. this.useCloseExponentialShadowMap = true;
  68543. return;
  68544. }
  68545. // PCF on cubemap would also be expensive
  68546. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68547. this.usePoissonSampling = true;
  68548. return;
  68549. }
  68550. }
  68551. // Weblg1 fallback for PCF.
  68552. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68553. if (this._scene.getEngine().webGLVersion === 1) {
  68554. this.usePoissonSampling = true;
  68555. return;
  68556. }
  68557. }
  68558. if (this._filter === value) {
  68559. return;
  68560. }
  68561. this._filter = value;
  68562. this._disposeBlurPostProcesses();
  68563. this._applyFilterValues();
  68564. this._light._markMeshesAsLightDirty();
  68565. },
  68566. enumerable: true,
  68567. configurable: true
  68568. });
  68569. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  68570. /**
  68571. * Gets if the current filter is set to Poisson Sampling.
  68572. */
  68573. get: function () {
  68574. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  68575. },
  68576. /**
  68577. * Sets the current filter to Poisson Sampling.
  68578. */
  68579. set: function (value) {
  68580. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  68581. return;
  68582. }
  68583. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  68584. },
  68585. enumerable: true,
  68586. configurable: true
  68587. });
  68588. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  68589. /**
  68590. * Gets if the current filter is set to VSM.
  68591. * DEPRECATED. Should use useExponentialShadowMap instead.
  68592. */
  68593. get: function () {
  68594. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68595. return this.useExponentialShadowMap;
  68596. },
  68597. /**
  68598. * Sets the current filter is to VSM.
  68599. * DEPRECATED. Should use useExponentialShadowMap instead.
  68600. */
  68601. set: function (value) {
  68602. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68603. this.useExponentialShadowMap = value;
  68604. },
  68605. enumerable: true,
  68606. configurable: true
  68607. });
  68608. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  68609. /**
  68610. * Gets if the current filter is set to blurred VSM.
  68611. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68612. */
  68613. get: function () {
  68614. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68615. return this.useBlurExponentialShadowMap;
  68616. },
  68617. /**
  68618. * Sets the current filter is to blurred VSM.
  68619. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68620. */
  68621. set: function (value) {
  68622. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68623. this.useBlurExponentialShadowMap = value;
  68624. },
  68625. enumerable: true,
  68626. configurable: true
  68627. });
  68628. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  68629. /**
  68630. * Gets if the current filter is set to ESM.
  68631. */
  68632. get: function () {
  68633. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  68634. },
  68635. /**
  68636. * Sets the current filter is to ESM.
  68637. */
  68638. set: function (value) {
  68639. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  68640. return;
  68641. }
  68642. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68643. },
  68644. enumerable: true,
  68645. configurable: true
  68646. });
  68647. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  68648. /**
  68649. * Gets if the current filter is set to filtered ESM.
  68650. */
  68651. get: function () {
  68652. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  68653. },
  68654. /**
  68655. * Gets if the current filter is set to filtered ESM.
  68656. */
  68657. set: function (value) {
  68658. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68659. return;
  68660. }
  68661. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68662. },
  68663. enumerable: true,
  68664. configurable: true
  68665. });
  68666. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  68667. /**
  68668. * Gets if the current filter is set to "close ESM" (using the inverse of the
  68669. * exponential to prevent steep falloff artifacts).
  68670. */
  68671. get: function () {
  68672. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  68673. },
  68674. /**
  68675. * Sets the current filter to "close ESM" (using the inverse of the
  68676. * exponential to prevent steep falloff artifacts).
  68677. */
  68678. set: function (value) {
  68679. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  68680. return;
  68681. }
  68682. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68683. },
  68684. enumerable: true,
  68685. configurable: true
  68686. });
  68687. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  68688. /**
  68689. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  68690. * exponential to prevent steep falloff artifacts).
  68691. */
  68692. get: function () {
  68693. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  68694. },
  68695. /**
  68696. * Sets the current filter to filtered "close ESM" (using the inverse of the
  68697. * exponential to prevent steep falloff artifacts).
  68698. */
  68699. set: function (value) {
  68700. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68701. return;
  68702. }
  68703. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68704. },
  68705. enumerable: true,
  68706. configurable: true
  68707. });
  68708. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  68709. /**
  68710. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  68711. */
  68712. get: function () {
  68713. return this.filter === ShadowGenerator.FILTER_PCF;
  68714. },
  68715. /**
  68716. * Sets the current filter to "PCF" (percentage closer filtering).
  68717. */
  68718. set: function (value) {
  68719. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  68720. return;
  68721. }
  68722. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  68723. },
  68724. enumerable: true,
  68725. configurable: true
  68726. });
  68727. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  68728. /**
  68729. * Gets the PCF or PCSS Quality.
  68730. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  68731. */
  68732. get: function () {
  68733. return this._filteringQuality;
  68734. },
  68735. /**
  68736. * Sets the PCF or PCSS Quality.
  68737. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  68738. */
  68739. set: function (filteringQuality) {
  68740. this._filteringQuality = filteringQuality;
  68741. },
  68742. enumerable: true,
  68743. configurable: true
  68744. });
  68745. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  68746. /**
  68747. * Gets if the current filter is set to "PCSS" (contact hardening).
  68748. */
  68749. get: function () {
  68750. return this.filter === ShadowGenerator.FILTER_PCSS;
  68751. },
  68752. /**
  68753. * Sets the current filter to "PCSS" (contact hardening).
  68754. */
  68755. set: function (value) {
  68756. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  68757. return;
  68758. }
  68759. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  68760. },
  68761. enumerable: true,
  68762. configurable: true
  68763. });
  68764. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  68765. /**
  68766. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  68767. * Using a ratio helps keeping shape stability independently of the map size.
  68768. *
  68769. * It does not account for the light projection as it was having too much
  68770. * instability during the light setup or during light position changes.
  68771. *
  68772. * Only valid if useContactHardeningShadow is true.
  68773. */
  68774. get: function () {
  68775. return this._contactHardeningLightSizeUVRatio;
  68776. },
  68777. /**
  68778. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  68779. * Using a ratio helps keeping shape stability independently of the map size.
  68780. *
  68781. * It does not account for the light projection as it was having too much
  68782. * instability during the light setup or during light position changes.
  68783. *
  68784. * Only valid if useContactHardeningShadow is true.
  68785. */
  68786. set: function (contactHardeningLightSizeUVRatio) {
  68787. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  68788. },
  68789. enumerable: true,
  68790. configurable: true
  68791. });
  68792. /**
  68793. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  68794. * 0 means strongest and 1 would means no shadow.
  68795. * @returns the darkness.
  68796. */
  68797. ShadowGenerator.prototype.getDarkness = function () {
  68798. return this._darkness;
  68799. };
  68800. /**
  68801. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  68802. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  68803. * @returns the shadow generator allowing fluent coding.
  68804. */
  68805. ShadowGenerator.prototype.setDarkness = function (darkness) {
  68806. if (darkness >= 1.0)
  68807. this._darkness = 1.0;
  68808. else if (darkness <= 0.0)
  68809. this._darkness = 0.0;
  68810. else
  68811. this._darkness = darkness;
  68812. return this;
  68813. };
  68814. /**
  68815. * Sets the ability to have transparent shadow (boolean).
  68816. * @param transparent True if transparent else False
  68817. * @returns the shadow generator allowing fluent coding
  68818. */
  68819. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  68820. this._transparencyShadow = transparent;
  68821. return this;
  68822. };
  68823. /**
  68824. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  68825. * @returns The render target texture if present otherwise, null
  68826. */
  68827. ShadowGenerator.prototype.getShadowMap = function () {
  68828. return this._shadowMap;
  68829. };
  68830. /**
  68831. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  68832. * @returns The render target texture if the shadow map is present otherwise, null
  68833. */
  68834. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  68835. if (this._shadowMap2) {
  68836. return this._shadowMap2;
  68837. }
  68838. return this._shadowMap;
  68839. };
  68840. /**
  68841. * Helper function to add a mesh and its descendants to the list of shadow casters.
  68842. * @param mesh Mesh to add
  68843. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  68844. * @returns the Shadow Generator itself
  68845. */
  68846. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  68847. if (includeDescendants === void 0) { includeDescendants = true; }
  68848. var _a;
  68849. if (!this._shadowMap) {
  68850. return this;
  68851. }
  68852. if (!this._shadowMap.renderList) {
  68853. this._shadowMap.renderList = [];
  68854. }
  68855. this._shadowMap.renderList.push(mesh);
  68856. if (includeDescendants) {
  68857. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  68858. }
  68859. return this;
  68860. };
  68861. /**
  68862. * Helper function to remove a mesh and its descendants from the list of shadow casters
  68863. * @param mesh Mesh to remove
  68864. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  68865. * @returns the Shadow Generator itself
  68866. */
  68867. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  68868. if (includeDescendants === void 0) { includeDescendants = true; }
  68869. if (!this._shadowMap || !this._shadowMap.renderList) {
  68870. return this;
  68871. }
  68872. var index = this._shadowMap.renderList.indexOf(mesh);
  68873. if (index !== -1) {
  68874. this._shadowMap.renderList.splice(index, 1);
  68875. }
  68876. if (includeDescendants) {
  68877. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  68878. var child = _a[_i];
  68879. this.removeShadowCaster(child);
  68880. }
  68881. }
  68882. return this;
  68883. };
  68884. /**
  68885. * Returns the associated light object.
  68886. * @returns the light generating the shadow
  68887. */
  68888. ShadowGenerator.prototype.getLight = function () {
  68889. return this._light;
  68890. };
  68891. ShadowGenerator.prototype._initializeGenerator = function () {
  68892. this._light._markMeshesAsLightDirty();
  68893. this._initializeShadowMap();
  68894. };
  68895. ShadowGenerator.prototype._initializeShadowMap = function () {
  68896. var _this = this;
  68897. // Render target
  68898. var engine = this._scene.getEngine();
  68899. if (engine.webGLVersion > 1) {
  68900. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  68901. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  68902. }
  68903. else {
  68904. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  68905. }
  68906. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68907. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68908. this._shadowMap.anisotropicFilteringLevel = 1;
  68909. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68910. this._shadowMap.renderParticles = false;
  68911. this._shadowMap.ignoreCameraViewport = true;
  68912. // Record Face Index before render.
  68913. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  68914. _this._currentFaceIndex = faceIndex;
  68915. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68916. engine.setColorWrite(false);
  68917. }
  68918. });
  68919. // Custom render function.
  68920. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  68921. // Blur if required afer render.
  68922. this._shadowMap.onAfterUnbindObservable.add(function () {
  68923. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68924. engine.setColorWrite(true);
  68925. }
  68926. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  68927. return;
  68928. }
  68929. var shadowMap = _this.getShadowMapForRendering();
  68930. if (shadowMap) {
  68931. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  68932. }
  68933. });
  68934. // Clear according to the chosen filter.
  68935. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  68936. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  68937. this._shadowMap.onClearObservable.add(function (engine) {
  68938. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  68939. engine.clear(clearOne, false, true, false);
  68940. }
  68941. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  68942. engine.clear(clearZero, true, true, false);
  68943. }
  68944. else {
  68945. engine.clear(clearOne, true, true, false);
  68946. }
  68947. });
  68948. };
  68949. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  68950. var _this = this;
  68951. var engine = this._scene.getEngine();
  68952. var targetSize = this._mapSize / this.blurScale;
  68953. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  68954. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  68955. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68956. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68957. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68958. }
  68959. if (this.useKernelBlur) {
  68960. 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);
  68961. this._kernelBlurXPostprocess.width = targetSize;
  68962. this._kernelBlurXPostprocess.height = targetSize;
  68963. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  68964. effect.setTexture("textureSampler", _this._shadowMap);
  68965. });
  68966. 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);
  68967. this._kernelBlurXPostprocess.autoClear = false;
  68968. this._kernelBlurYPostprocess.autoClear = false;
  68969. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68970. this._kernelBlurXPostprocess.packedFloat = true;
  68971. this._kernelBlurYPostprocess.packedFloat = true;
  68972. }
  68973. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  68974. }
  68975. else {
  68976. 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);
  68977. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  68978. effect.setFloat2("screenSize", targetSize, targetSize);
  68979. effect.setTexture("textureSampler", _this._shadowMap);
  68980. });
  68981. this._boxBlurPostprocess.autoClear = false;
  68982. this._blurPostProcesses = [this._boxBlurPostprocess];
  68983. }
  68984. };
  68985. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68986. var index;
  68987. var engine = this._scene.getEngine();
  68988. if (depthOnlySubMeshes.length) {
  68989. engine.setColorWrite(false);
  68990. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68991. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  68992. }
  68993. engine.setColorWrite(true);
  68994. }
  68995. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68996. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  68997. }
  68998. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68999. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  69000. }
  69001. if (this._transparencyShadow) {
  69002. for (index = 0; index < transparentSubMeshes.length; index++) {
  69003. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  69004. }
  69005. }
  69006. };
  69007. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  69008. var _this = this;
  69009. var mesh = subMesh.getRenderingMesh();
  69010. var scene = this._scene;
  69011. var engine = scene.getEngine();
  69012. var material = subMesh.getMaterial();
  69013. if (!material) {
  69014. return;
  69015. }
  69016. // Culling
  69017. engine.setState(material.backFaceCulling);
  69018. // Managing instances
  69019. var batch = mesh._getInstancesRenderList(subMesh._id);
  69020. if (batch.mustReturn) {
  69021. return;
  69022. }
  69023. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69024. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  69025. engine.enableEffect(this._effect);
  69026. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69027. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  69028. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  69029. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69030. this._effect.setVector3("lightData", this._cachedDirection);
  69031. }
  69032. else {
  69033. this._effect.setVector3("lightData", this._cachedPosition);
  69034. }
  69035. if (scene.activeCamera) {
  69036. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  69037. }
  69038. // Alpha test
  69039. if (material && material.needAlphaTesting()) {
  69040. var alphaTexture = material.getAlphaTestTexture();
  69041. if (alphaTexture) {
  69042. this._effect.setTexture("diffuseSampler", alphaTexture);
  69043. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  69044. }
  69045. }
  69046. // Bones
  69047. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69048. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  69049. }
  69050. // Morph targets
  69051. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  69052. if (this.forceBackFacesOnly) {
  69053. engine.setState(true, 0, false, true);
  69054. }
  69055. // Draw
  69056. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69057. if (this.forceBackFacesOnly) {
  69058. engine.setState(true, 0, false, false);
  69059. }
  69060. }
  69061. else {
  69062. // Need to reset refresh rate of the shadowMap
  69063. if (this._shadowMap) {
  69064. this._shadowMap.resetRefreshCounter();
  69065. }
  69066. }
  69067. };
  69068. ShadowGenerator.prototype._applyFilterValues = function () {
  69069. if (!this._shadowMap) {
  69070. return;
  69071. }
  69072. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  69073. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  69074. }
  69075. else {
  69076. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69077. }
  69078. };
  69079. /**
  69080. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69081. * @param onCompiled Callback triggered at the and of the effects compilation
  69082. * @param options Sets of optional options forcing the compilation with different modes
  69083. */
  69084. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  69085. var _this = this;
  69086. var localOptions = __assign({ useInstances: false }, options);
  69087. var shadowMap = this.getShadowMap();
  69088. if (!shadowMap) {
  69089. if (onCompiled) {
  69090. onCompiled(this);
  69091. }
  69092. return;
  69093. }
  69094. var renderList = shadowMap.renderList;
  69095. if (!renderList) {
  69096. if (onCompiled) {
  69097. onCompiled(this);
  69098. }
  69099. return;
  69100. }
  69101. var subMeshes = new Array();
  69102. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  69103. var mesh = renderList_1[_i];
  69104. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  69105. }
  69106. if (subMeshes.length === 0) {
  69107. if (onCompiled) {
  69108. onCompiled(this);
  69109. }
  69110. return;
  69111. }
  69112. var currentIndex = 0;
  69113. var checkReady = function () {
  69114. if (!_this._scene || !_this._scene.getEngine()) {
  69115. return;
  69116. }
  69117. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  69118. currentIndex++;
  69119. if (currentIndex >= subMeshes.length) {
  69120. if (onCompiled) {
  69121. onCompiled(_this);
  69122. }
  69123. return;
  69124. }
  69125. }
  69126. setTimeout(checkReady, 16);
  69127. };
  69128. checkReady();
  69129. };
  69130. /**
  69131. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69132. * @param options Sets of optional options forcing the compilation with different modes
  69133. * @returns A promise that resolves when the compilation completes
  69134. */
  69135. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  69136. var _this = this;
  69137. return new Promise(function (resolve) {
  69138. _this.forceCompilation(function () {
  69139. resolve();
  69140. }, options);
  69141. });
  69142. };
  69143. /**
  69144. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  69145. * @param subMesh The submesh we want to render in the shadow map
  69146. * @param useInstances Defines wether will draw in the map using instances
  69147. * @returns true if ready otherwise, false
  69148. */
  69149. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  69150. var defines = [];
  69151. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69152. defines.push("#define FLOAT");
  69153. }
  69154. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69155. defines.push("#define ESM");
  69156. }
  69157. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  69158. defines.push("#define DEPTHTEXTURE");
  69159. }
  69160. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69161. var mesh = subMesh.getMesh();
  69162. var material = subMesh.getMaterial();
  69163. // Normal bias.
  69164. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69165. attribs.push(BABYLON.VertexBuffer.NormalKind);
  69166. defines.push("#define NORMAL");
  69167. if (mesh.nonUniformScaling) {
  69168. defines.push("#define NONUNIFORMSCALING");
  69169. }
  69170. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69171. defines.push("#define DIRECTIONINLIGHTDATA");
  69172. }
  69173. }
  69174. // Alpha test
  69175. if (material && material.needAlphaTesting()) {
  69176. var alphaTexture = material.getAlphaTestTexture();
  69177. if (alphaTexture) {
  69178. defines.push("#define ALPHATEST");
  69179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69180. attribs.push(BABYLON.VertexBuffer.UVKind);
  69181. defines.push("#define UV1");
  69182. }
  69183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69184. if (alphaTexture.coordinatesIndex === 1) {
  69185. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69186. defines.push("#define UV2");
  69187. }
  69188. }
  69189. }
  69190. }
  69191. // Bones
  69192. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69193. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69194. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69195. if (mesh.numBoneInfluencers > 4) {
  69196. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69197. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69198. }
  69199. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69200. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69201. }
  69202. else {
  69203. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69204. }
  69205. // Morph targets
  69206. var manager = mesh.morphTargetManager;
  69207. var morphInfluencers = 0;
  69208. if (manager) {
  69209. if (manager.numInfluencers > 0) {
  69210. defines.push("#define MORPHTARGETS");
  69211. morphInfluencers = manager.numInfluencers;
  69212. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  69213. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  69214. }
  69215. }
  69216. // Instances
  69217. if (useInstances) {
  69218. defines.push("#define INSTANCES");
  69219. attribs.push("world0");
  69220. attribs.push("world1");
  69221. attribs.push("world2");
  69222. attribs.push("world3");
  69223. }
  69224. // Get correct effect
  69225. var join = defines.join("\n");
  69226. if (this._cachedDefines !== join) {
  69227. this._cachedDefines = join;
  69228. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  69229. }
  69230. if (!this._effect.isReady()) {
  69231. return false;
  69232. }
  69233. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69234. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  69235. this._initializeBlurRTTAndPostProcesses();
  69236. }
  69237. }
  69238. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  69239. return false;
  69240. }
  69241. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  69242. return false;
  69243. }
  69244. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  69245. return false;
  69246. }
  69247. return true;
  69248. };
  69249. /**
  69250. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  69251. * @param defines Defines of the material we want to update
  69252. * @param lightIndex Index of the light in the enabled light list of the material
  69253. */
  69254. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  69255. var scene = this._scene;
  69256. var light = this._light;
  69257. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69258. return;
  69259. }
  69260. defines["SHADOW" + lightIndex] = true;
  69261. if (this.useContactHardeningShadow) {
  69262. defines["SHADOWPCSS" + lightIndex] = true;
  69263. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69264. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69265. }
  69266. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69267. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69268. }
  69269. // else default to high.
  69270. }
  69271. if (this.usePercentageCloserFiltering) {
  69272. defines["SHADOWPCF" + lightIndex] = true;
  69273. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69274. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69275. }
  69276. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69277. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69278. }
  69279. // else default to high.
  69280. }
  69281. else if (this.usePoissonSampling) {
  69282. defines["SHADOWPOISSON" + lightIndex] = true;
  69283. }
  69284. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69285. defines["SHADOWESM" + lightIndex] = true;
  69286. }
  69287. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69288. defines["SHADOWCLOSEESM" + lightIndex] = true;
  69289. }
  69290. if (light.needCube()) {
  69291. defines["SHADOWCUBE" + lightIndex] = true;
  69292. }
  69293. };
  69294. /**
  69295. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  69296. * defined in the generator but impacting the effect).
  69297. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  69298. * @param effect The effect we are binfing the information for
  69299. */
  69300. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  69301. var light = this._light;
  69302. var scene = this._scene;
  69303. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69304. return;
  69305. }
  69306. var camera = scene.activeCamera;
  69307. if (!camera) {
  69308. return;
  69309. }
  69310. var shadowMap = this.getShadowMap();
  69311. if (!shadowMap) {
  69312. return;
  69313. }
  69314. if (!light.needCube()) {
  69315. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  69316. }
  69317. // Only PCF uses depth stencil texture.
  69318. if (this._filter === ShadowGenerator.FILTER_PCF) {
  69319. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69320. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69321. }
  69322. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  69323. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69324. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  69325. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69326. }
  69327. else {
  69328. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69329. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  69330. }
  69331. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  69332. };
  69333. /**
  69334. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  69335. * (eq to shadow prjection matrix * light transform matrix)
  69336. * @returns The transform matrix used to create the shadow map
  69337. */
  69338. ShadowGenerator.prototype.getTransformMatrix = function () {
  69339. var scene = this._scene;
  69340. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  69341. return this._transformMatrix;
  69342. }
  69343. this._currentRenderID = scene.getRenderId();
  69344. this._currentFaceIndexCache = this._currentFaceIndex;
  69345. var lightPosition = this._light.position;
  69346. if (this._light.computeTransformedInformation()) {
  69347. lightPosition = this._light.transformedPosition;
  69348. }
  69349. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  69350. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  69351. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  69352. }
  69353. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  69354. this._cachedPosition.copyFrom(lightPosition);
  69355. this._cachedDirection.copyFrom(this._lightDirection);
  69356. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  69357. var shadowMap = this.getShadowMap();
  69358. if (shadowMap) {
  69359. var renderList = shadowMap.renderList;
  69360. if (renderList) {
  69361. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  69362. }
  69363. }
  69364. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  69365. }
  69366. return this._transformMatrix;
  69367. };
  69368. /**
  69369. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  69370. * Cube and 2D textures for instance.
  69371. */
  69372. ShadowGenerator.prototype.recreateShadowMap = function () {
  69373. var shadowMap = this._shadowMap;
  69374. if (!shadowMap) {
  69375. return;
  69376. }
  69377. // Track render list.
  69378. var renderList = shadowMap.renderList;
  69379. // Clean up existing data.
  69380. this._disposeRTTandPostProcesses();
  69381. // Reinitializes.
  69382. this._initializeGenerator();
  69383. // Reaffect the filter to ensure a correct fallback if necessary.
  69384. this.filter = this.filter;
  69385. // Reaffect the filter.
  69386. this._applyFilterValues();
  69387. // Reaffect Render List.
  69388. this._shadowMap.renderList = renderList;
  69389. };
  69390. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  69391. if (this._shadowMap2) {
  69392. this._shadowMap2.dispose();
  69393. this._shadowMap2 = null;
  69394. }
  69395. if (this._boxBlurPostprocess) {
  69396. this._boxBlurPostprocess.dispose();
  69397. this._boxBlurPostprocess = null;
  69398. }
  69399. if (this._kernelBlurXPostprocess) {
  69400. this._kernelBlurXPostprocess.dispose();
  69401. this._kernelBlurXPostprocess = null;
  69402. }
  69403. if (this._kernelBlurYPostprocess) {
  69404. this._kernelBlurYPostprocess.dispose();
  69405. this._kernelBlurYPostprocess = null;
  69406. }
  69407. this._blurPostProcesses = [];
  69408. };
  69409. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  69410. if (this._shadowMap) {
  69411. this._shadowMap.dispose();
  69412. this._shadowMap = null;
  69413. }
  69414. this._disposeBlurPostProcesses();
  69415. };
  69416. /**
  69417. * Disposes the ShadowGenerator.
  69418. * Returns nothing.
  69419. */
  69420. ShadowGenerator.prototype.dispose = function () {
  69421. this._disposeRTTandPostProcesses();
  69422. if (this._light) {
  69423. this._light._shadowGenerator = null;
  69424. this._light._markMeshesAsLightDirty();
  69425. }
  69426. };
  69427. /**
  69428. * Serializes the shadow generator setup to a json object.
  69429. * @returns The serialized JSON object
  69430. */
  69431. ShadowGenerator.prototype.serialize = function () {
  69432. var serializationObject = {};
  69433. var shadowMap = this.getShadowMap();
  69434. if (!shadowMap) {
  69435. return serializationObject;
  69436. }
  69437. serializationObject.lightId = this._light.id;
  69438. serializationObject.mapSize = shadowMap.getRenderSize();
  69439. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  69440. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  69441. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69442. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69443. serializationObject.usePoissonSampling = this.usePoissonSampling;
  69444. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  69445. serializationObject.depthScale = this.depthScale;
  69446. serializationObject.darkness = this.getDarkness();
  69447. serializationObject.blurBoxOffset = this.blurBoxOffset;
  69448. serializationObject.blurKernel = this.blurKernel;
  69449. serializationObject.blurScale = this.blurScale;
  69450. serializationObject.useKernelBlur = this.useKernelBlur;
  69451. serializationObject.transparencyShadow = this._transparencyShadow;
  69452. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  69453. serializationObject.bias = this.bias;
  69454. serializationObject.normalBias = this.normalBias;
  69455. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  69456. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  69457. serializationObject.filteringQuality = this.filteringQuality;
  69458. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  69459. serializationObject.renderList = [];
  69460. if (shadowMap.renderList) {
  69461. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  69462. var mesh = shadowMap.renderList[meshIndex];
  69463. serializationObject.renderList.push(mesh.id);
  69464. }
  69465. }
  69466. return serializationObject;
  69467. };
  69468. /**
  69469. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  69470. * @param parsedShadowGenerator The JSON object to parse
  69471. * @param scene The scene to create the shadow map for
  69472. * @returns The parsed shadow generator
  69473. */
  69474. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  69475. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  69476. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  69477. var shadowMap = shadowGenerator.getShadowMap();
  69478. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  69479. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  69480. meshes.forEach(function (mesh) {
  69481. if (!shadowMap) {
  69482. return;
  69483. }
  69484. if (!shadowMap.renderList) {
  69485. shadowMap.renderList = [];
  69486. }
  69487. shadowMap.renderList.push(mesh);
  69488. });
  69489. }
  69490. if (parsedShadowGenerator.usePoissonSampling) {
  69491. shadowGenerator.usePoissonSampling = true;
  69492. }
  69493. else if (parsedShadowGenerator.useExponentialShadowMap) {
  69494. shadowGenerator.useExponentialShadowMap = true;
  69495. }
  69496. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  69497. shadowGenerator.useBlurExponentialShadowMap = true;
  69498. }
  69499. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  69500. shadowGenerator.useCloseExponentialShadowMap = true;
  69501. }
  69502. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  69503. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  69504. }
  69505. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  69506. shadowGenerator.usePercentageCloserFiltering = true;
  69507. }
  69508. else if (parsedShadowGenerator.useContactHardeningShadow) {
  69509. shadowGenerator.useContactHardeningShadow = true;
  69510. }
  69511. if (parsedShadowGenerator.filteringQuality) {
  69512. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  69513. }
  69514. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  69515. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  69516. }
  69517. // Backward compat
  69518. else if (parsedShadowGenerator.useVarianceShadowMap) {
  69519. shadowGenerator.useExponentialShadowMap = true;
  69520. }
  69521. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  69522. shadowGenerator.useBlurExponentialShadowMap = true;
  69523. }
  69524. if (parsedShadowGenerator.depthScale) {
  69525. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  69526. }
  69527. if (parsedShadowGenerator.blurScale) {
  69528. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  69529. }
  69530. if (parsedShadowGenerator.blurBoxOffset) {
  69531. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  69532. }
  69533. if (parsedShadowGenerator.useKernelBlur) {
  69534. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  69535. }
  69536. if (parsedShadowGenerator.blurKernel) {
  69537. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  69538. }
  69539. if (parsedShadowGenerator.bias !== undefined) {
  69540. shadowGenerator.bias = parsedShadowGenerator.bias;
  69541. }
  69542. if (parsedShadowGenerator.normalBias !== undefined) {
  69543. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  69544. }
  69545. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  69546. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  69547. }
  69548. if (parsedShadowGenerator.darkness) {
  69549. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  69550. }
  69551. if (parsedShadowGenerator.transparencyShadow) {
  69552. shadowGenerator.setTransparencyShadow(true);
  69553. }
  69554. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  69555. return shadowGenerator;
  69556. };
  69557. /**
  69558. * Shadow generator mode None: no filtering applied.
  69559. */
  69560. ShadowGenerator.FILTER_NONE = 0;
  69561. /**
  69562. * Shadow generator mode ESM: Exponential Shadow Mapping.
  69563. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69564. */
  69565. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  69566. /**
  69567. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  69568. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  69569. */
  69570. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  69571. /**
  69572. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  69573. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69574. */
  69575. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  69576. /**
  69577. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  69578. * edge artifacts on steep falloff.
  69579. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69580. */
  69581. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  69582. /**
  69583. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  69584. * edge artifacts on steep falloff.
  69585. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69586. */
  69587. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  69588. /**
  69589. * Shadow generator mode PCF: Percentage Closer Filtering
  69590. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69591. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  69592. */
  69593. ShadowGenerator.FILTER_PCF = 6;
  69594. /**
  69595. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  69596. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69597. * Contact Hardening
  69598. */
  69599. ShadowGenerator.FILTER_PCSS = 7;
  69600. /**
  69601. * Reserved for PCF and PCSS
  69602. * Highest Quality.
  69603. *
  69604. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  69605. *
  69606. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  69607. */
  69608. ShadowGenerator.QUALITY_HIGH = 0;
  69609. /**
  69610. * Reserved for PCF and PCSS
  69611. * Good tradeoff for quality/perf cross devices
  69612. *
  69613. * Execute PCF on a 3*3 kernel.
  69614. *
  69615. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  69616. */
  69617. ShadowGenerator.QUALITY_MEDIUM = 1;
  69618. /**
  69619. * Reserved for PCF and PCSS
  69620. * The lowest quality but the fastest.
  69621. *
  69622. * Execute PCF on a 1*1 kernel.
  69623. *
  69624. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  69625. */
  69626. ShadowGenerator.QUALITY_LOW = 2;
  69627. return ShadowGenerator;
  69628. }());
  69629. BABYLON.ShadowGenerator = ShadowGenerator;
  69630. })(BABYLON || (BABYLON = {}));
  69631. //# sourceMappingURL=babylon.shadowGenerator.js.map
  69632. var BABYLON;
  69633. (function (BABYLON) {
  69634. var DefaultLoadingScreen = /** @class */ (function () {
  69635. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  69636. if (_loadingText === void 0) { _loadingText = ""; }
  69637. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  69638. var _this = this;
  69639. this._renderingCanvas = _renderingCanvas;
  69640. this._loadingText = _loadingText;
  69641. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  69642. // Resize
  69643. this._resizeLoadingUI = function () {
  69644. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  69645. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  69646. if (!_this._loadingDiv) {
  69647. return;
  69648. }
  69649. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  69650. _this._loadingDiv.style.left = canvasRect.left + "px";
  69651. _this._loadingDiv.style.top = canvasRect.top + "px";
  69652. _this._loadingDiv.style.width = canvasRect.width + "px";
  69653. _this._loadingDiv.style.height = canvasRect.height + "px";
  69654. };
  69655. }
  69656. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  69657. if (this._loadingDiv) {
  69658. // Do not add a loading screen if there is already one
  69659. return;
  69660. }
  69661. this._loadingDiv = document.createElement("div");
  69662. this._loadingDiv.id = "babylonjsLoadingDiv";
  69663. this._loadingDiv.style.opacity = "0";
  69664. this._loadingDiv.style.transition = "opacity 1.5s ease";
  69665. this._loadingDiv.style.pointerEvents = "none";
  69666. // Loading text
  69667. this._loadingTextDiv = document.createElement("div");
  69668. this._loadingTextDiv.style.position = "absolute";
  69669. this._loadingTextDiv.style.left = "0";
  69670. this._loadingTextDiv.style.top = "50%";
  69671. this._loadingTextDiv.style.marginTop = "80px";
  69672. this._loadingTextDiv.style.width = "100%";
  69673. this._loadingTextDiv.style.height = "20px";
  69674. this._loadingTextDiv.style.fontFamily = "Arial";
  69675. this._loadingTextDiv.style.fontSize = "14px";
  69676. this._loadingTextDiv.style.color = "white";
  69677. this._loadingTextDiv.style.textAlign = "center";
  69678. this._loadingTextDiv.innerHTML = "Loading";
  69679. this._loadingDiv.appendChild(this._loadingTextDiv);
  69680. //set the predefined text
  69681. this._loadingTextDiv.innerHTML = this._loadingText;
  69682. // Generating keyframes
  69683. var style = document.createElement('style');
  69684. style.type = 'text/css';
  69685. 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 }";
  69686. style.innerHTML = keyFrames;
  69687. document.getElementsByTagName('head')[0].appendChild(style);
  69688. // Loading img
  69689. var imgBack = new Image();
  69690. 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";
  69691. imgBack.style.position = "absolute";
  69692. imgBack.style.left = "50%";
  69693. imgBack.style.top = "50%";
  69694. imgBack.style.marginLeft = "-60px";
  69695. imgBack.style.marginTop = "-60px";
  69696. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  69697. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  69698. imgBack.style.transformOrigin = "50% 50%";
  69699. imgBack.style.webkitTransformOrigin = "50% 50%";
  69700. this._loadingDiv.appendChild(imgBack);
  69701. this._resizeLoadingUI();
  69702. window.addEventListener("resize", this._resizeLoadingUI);
  69703. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  69704. document.body.appendChild(this._loadingDiv);
  69705. this._loadingDiv.style.opacity = "1";
  69706. };
  69707. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  69708. var _this = this;
  69709. if (!this._loadingDiv) {
  69710. return;
  69711. }
  69712. var onTransitionEnd = function () {
  69713. if (!_this._loadingDiv) {
  69714. return;
  69715. }
  69716. document.body.removeChild(_this._loadingDiv);
  69717. window.removeEventListener("resize", _this._resizeLoadingUI);
  69718. _this._loadingDiv = null;
  69719. };
  69720. this._loadingDiv.style.opacity = "0";
  69721. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  69722. };
  69723. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  69724. set: function (text) {
  69725. this._loadingText = text;
  69726. if (this._loadingTextDiv) {
  69727. this._loadingTextDiv.innerHTML = this._loadingText;
  69728. }
  69729. },
  69730. enumerable: true,
  69731. configurable: true
  69732. });
  69733. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  69734. get: function () {
  69735. return this._loadingDivBackgroundColor;
  69736. },
  69737. set: function (color) {
  69738. this._loadingDivBackgroundColor = color;
  69739. if (!this._loadingDiv) {
  69740. return;
  69741. }
  69742. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  69743. },
  69744. enumerable: true,
  69745. configurable: true
  69746. });
  69747. return DefaultLoadingScreen;
  69748. }());
  69749. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  69750. })(BABYLON || (BABYLON = {}));
  69751. //# sourceMappingURL=babylon.loadingScreen.js.map
  69752. var BABYLON;
  69753. (function (BABYLON) {
  69754. var SceneLoaderProgressEvent = /** @class */ (function () {
  69755. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  69756. this.lengthComputable = lengthComputable;
  69757. this.loaded = loaded;
  69758. this.total = total;
  69759. }
  69760. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  69761. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  69762. };
  69763. return SceneLoaderProgressEvent;
  69764. }());
  69765. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  69766. var SceneLoader = /** @class */ (function () {
  69767. function SceneLoader() {
  69768. }
  69769. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  69770. get: function () {
  69771. return 0;
  69772. },
  69773. enumerable: true,
  69774. configurable: true
  69775. });
  69776. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  69777. get: function () {
  69778. return 1;
  69779. },
  69780. enumerable: true,
  69781. configurable: true
  69782. });
  69783. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  69784. get: function () {
  69785. return 2;
  69786. },
  69787. enumerable: true,
  69788. configurable: true
  69789. });
  69790. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  69791. get: function () {
  69792. return 3;
  69793. },
  69794. enumerable: true,
  69795. configurable: true
  69796. });
  69797. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  69798. get: function () {
  69799. return SceneLoader._ForceFullSceneLoadingForIncremental;
  69800. },
  69801. set: function (value) {
  69802. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  69803. },
  69804. enumerable: true,
  69805. configurable: true
  69806. });
  69807. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  69808. get: function () {
  69809. return SceneLoader._ShowLoadingScreen;
  69810. },
  69811. set: function (value) {
  69812. SceneLoader._ShowLoadingScreen = value;
  69813. },
  69814. enumerable: true,
  69815. configurable: true
  69816. });
  69817. Object.defineProperty(SceneLoader, "loggingLevel", {
  69818. get: function () {
  69819. return SceneLoader._loggingLevel;
  69820. },
  69821. set: function (value) {
  69822. SceneLoader._loggingLevel = value;
  69823. },
  69824. enumerable: true,
  69825. configurable: true
  69826. });
  69827. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  69828. get: function () {
  69829. return SceneLoader._CleanBoneMatrixWeights;
  69830. },
  69831. set: function (value) {
  69832. SceneLoader._CleanBoneMatrixWeights = value;
  69833. },
  69834. enumerable: true,
  69835. configurable: true
  69836. });
  69837. SceneLoader._getDefaultPlugin = function () {
  69838. return SceneLoader._registeredPlugins[".babylon"];
  69839. };
  69840. SceneLoader._getPluginForExtension = function (extension) {
  69841. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  69842. if (registeredPlugin) {
  69843. return registeredPlugin;
  69844. }
  69845. 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");
  69846. return SceneLoader._getDefaultPlugin();
  69847. };
  69848. SceneLoader._getPluginForDirectLoad = function (data) {
  69849. for (var extension in SceneLoader._registeredPlugins) {
  69850. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  69851. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  69852. return SceneLoader._registeredPlugins[extension];
  69853. }
  69854. }
  69855. return SceneLoader._getDefaultPlugin();
  69856. };
  69857. SceneLoader._getPluginForFilename = function (sceneFilename) {
  69858. if (sceneFilename.name) {
  69859. sceneFilename = sceneFilename.name;
  69860. }
  69861. var queryStringPosition = sceneFilename.indexOf("?");
  69862. if (queryStringPosition !== -1) {
  69863. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  69864. }
  69865. var dotPosition = sceneFilename.lastIndexOf(".");
  69866. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  69867. return SceneLoader._getPluginForExtension(extension);
  69868. };
  69869. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  69870. SceneLoader._getDirectLoad = function (sceneFilename) {
  69871. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  69872. return sceneFilename.substr(5);
  69873. }
  69874. return null;
  69875. };
  69876. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  69877. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  69878. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  69879. var plugin;
  69880. if (registeredPlugin.plugin.createPlugin) {
  69881. plugin = registeredPlugin.plugin.createPlugin();
  69882. }
  69883. else {
  69884. plugin = registeredPlugin.plugin;
  69885. }
  69886. var useArrayBuffer = registeredPlugin.isBinary;
  69887. var database;
  69888. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  69889. var dataCallback = function (data, responseURL) {
  69890. if (scene.isDisposed) {
  69891. onError("Scene has been disposed");
  69892. return;
  69893. }
  69894. scene.database = database;
  69895. onSuccess(plugin, data, responseURL);
  69896. };
  69897. var request = null;
  69898. var pluginDisposed = false;
  69899. var onDisposeObservable = plugin.onDisposeObservable;
  69900. if (onDisposeObservable) {
  69901. onDisposeObservable.add(function () {
  69902. pluginDisposed = true;
  69903. if (request) {
  69904. request.abort();
  69905. request = null;
  69906. }
  69907. onDispose();
  69908. });
  69909. }
  69910. var manifestChecked = function () {
  69911. if (pluginDisposed) {
  69912. return;
  69913. }
  69914. var url = rootUrl + sceneFilename;
  69915. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  69916. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  69917. } : undefined, database, useArrayBuffer, function (request, exception) {
  69918. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  69919. });
  69920. };
  69921. if (directLoad) {
  69922. dataCallback(directLoad);
  69923. return plugin;
  69924. }
  69925. if (rootUrl.indexOf("file:") === -1) {
  69926. var engine = scene.getEngine();
  69927. var canUseOfflineSupport = engine.enableOfflineSupport;
  69928. if (canUseOfflineSupport) {
  69929. // Also check for exceptions
  69930. var exceptionFound = false;
  69931. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  69932. var regex = _a[_i];
  69933. if (regex.test(rootUrl + sceneFilename)) {
  69934. exceptionFound = true;
  69935. break;
  69936. }
  69937. }
  69938. canUseOfflineSupport = !exceptionFound;
  69939. }
  69940. if (canUseOfflineSupport) {
  69941. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  69942. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  69943. }
  69944. else {
  69945. manifestChecked();
  69946. }
  69947. }
  69948. // Loading file from disk via input file or drag'n'drop
  69949. else {
  69950. var fileOrString = sceneFilename;
  69951. if (fileOrString.name) { // File
  69952. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  69953. }
  69954. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  69955. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  69956. }
  69957. else {
  69958. onError("Unable to find file named " + sceneFilename);
  69959. }
  69960. }
  69961. return plugin;
  69962. };
  69963. // Public functions
  69964. SceneLoader.GetPluginForExtension = function (extension) {
  69965. return SceneLoader._getPluginForExtension(extension).plugin;
  69966. };
  69967. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  69968. return !!SceneLoader._registeredPlugins[extension];
  69969. };
  69970. SceneLoader.RegisterPlugin = function (plugin) {
  69971. if (typeof plugin.extensions === "string") {
  69972. var extension = plugin.extensions;
  69973. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69974. plugin: plugin,
  69975. isBinary: false
  69976. };
  69977. }
  69978. else {
  69979. var extensions = plugin.extensions;
  69980. Object.keys(extensions).forEach(function (extension) {
  69981. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69982. plugin: plugin,
  69983. isBinary: extensions[extension].isBinary
  69984. };
  69985. });
  69986. }
  69987. };
  69988. /**
  69989. * Import meshes into a scene
  69990. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69991. * @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)
  69992. * @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)
  69993. * @param scene the instance of BABYLON.Scene to append to
  69994. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  69995. * @param onProgress a callback with a progress event for each file being loaded
  69996. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69997. * @param pluginExtension the extension used to determine the plugin
  69998. * @returns The loaded plugin
  69999. */
  70000. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70001. if (sceneFilename === void 0) { sceneFilename = ""; }
  70002. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70003. if (onSuccess === void 0) { onSuccess = null; }
  70004. if (onProgress === void 0) { onProgress = null; }
  70005. if (onError === void 0) { onError = null; }
  70006. if (pluginExtension === void 0) { pluginExtension = null; }
  70007. if (!scene) {
  70008. BABYLON.Tools.Error("No scene available to import mesh to");
  70009. return null;
  70010. }
  70011. if (!sceneFilename) {
  70012. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70013. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70014. }
  70015. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70016. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70017. return null;
  70018. }
  70019. var loadingToken = {};
  70020. scene._addPendingData(loadingToken);
  70021. var disposeHandler = function () {
  70022. scene._removePendingData(loadingToken);
  70023. };
  70024. var errorHandler = function (message, exception) {
  70025. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  70026. if (onError) {
  70027. onError(scene, errorMessage, exception);
  70028. }
  70029. else {
  70030. BABYLON.Tools.Error(errorMessage);
  70031. // should the exception be thrown?
  70032. }
  70033. disposeHandler();
  70034. };
  70035. var progressHandler = onProgress ? function (event) {
  70036. try {
  70037. onProgress(event);
  70038. }
  70039. catch (e) {
  70040. errorHandler("Error in onProgress callback", e);
  70041. }
  70042. } : undefined;
  70043. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  70044. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  70045. if (onSuccess) {
  70046. try {
  70047. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  70048. }
  70049. catch (e) {
  70050. errorHandler("Error in onSuccess callback", e);
  70051. }
  70052. }
  70053. scene._removePendingData(loadingToken);
  70054. };
  70055. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70056. if (plugin.rewriteRootURL) {
  70057. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  70058. }
  70059. if (sceneFilename === "") {
  70060. if (sceneFilename === "") {
  70061. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70062. }
  70063. }
  70064. if (plugin.importMesh) {
  70065. var syncedPlugin = plugin;
  70066. var meshes = new Array();
  70067. var particleSystems = new Array();
  70068. var skeletons = new Array();
  70069. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  70070. return;
  70071. }
  70072. scene.loadingPluginName = plugin.name;
  70073. successHandler(meshes, particleSystems, skeletons, []);
  70074. }
  70075. else {
  70076. var asyncedPlugin = plugin;
  70077. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  70078. scene.loadingPluginName = plugin.name;
  70079. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  70080. }).catch(function (error) {
  70081. errorHandler(error.message, error);
  70082. });
  70083. }
  70084. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70085. };
  70086. /**
  70087. * Import meshes into a scene
  70088. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70089. * @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)
  70090. * @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)
  70091. * @param scene the instance of BABYLON.Scene to append to
  70092. * @param onProgress a callback with a progress event for each file being loaded
  70093. * @param pluginExtension the extension used to determine the plugin
  70094. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  70095. */
  70096. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70097. if (sceneFilename === void 0) { sceneFilename = ""; }
  70098. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70099. if (onProgress === void 0) { onProgress = null; }
  70100. if (pluginExtension === void 0) { pluginExtension = null; }
  70101. return new Promise(function (resolve, reject) {
  70102. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  70103. resolve({
  70104. meshes: meshes,
  70105. particleSystems: particleSystems,
  70106. skeletons: skeletons,
  70107. animationGroups: animationGroups
  70108. });
  70109. }, onProgress, function (scene, message, exception) {
  70110. reject(exception || new Error(message));
  70111. }, pluginExtension);
  70112. });
  70113. };
  70114. /**
  70115. * Load a scene
  70116. * @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)
  70117. * @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)
  70118. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70119. * @param onSuccess a callback with the scene when import succeeds
  70120. * @param onProgress a callback with a progress event for each file being loaded
  70121. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70122. * @param pluginExtension the extension used to determine the plugin
  70123. * @returns The loaded plugin
  70124. */
  70125. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  70126. if (onSuccess === void 0) { onSuccess = null; }
  70127. if (onProgress === void 0) { onProgress = null; }
  70128. if (onError === void 0) { onError = null; }
  70129. if (pluginExtension === void 0) { pluginExtension = null; }
  70130. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  70131. };
  70132. /**
  70133. * Load a scene
  70134. * @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)
  70135. * @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)
  70136. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70137. * @param onProgress a callback with a progress event for each file being loaded
  70138. * @param pluginExtension the extension used to determine the plugin
  70139. * @returns The loaded scene
  70140. */
  70141. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  70142. if (onProgress === void 0) { onProgress = null; }
  70143. if (pluginExtension === void 0) { pluginExtension = null; }
  70144. return new Promise(function (resolve, reject) {
  70145. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  70146. resolve(scene);
  70147. }, onProgress, function (scene, message, exception) {
  70148. reject(exception || new Error(message));
  70149. }, pluginExtension);
  70150. });
  70151. };
  70152. /**
  70153. * Append a scene
  70154. * @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)
  70155. * @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)
  70156. * @param scene is the instance of BABYLON.Scene to append to
  70157. * @param onSuccess a callback with the scene when import succeeds
  70158. * @param onProgress a callback with a progress event for each file being loaded
  70159. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70160. * @param pluginExtension the extension used to determine the plugin
  70161. * @returns The loaded plugin
  70162. */
  70163. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70164. if (sceneFilename === void 0) { sceneFilename = ""; }
  70165. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70166. if (onSuccess === void 0) { onSuccess = null; }
  70167. if (onProgress === void 0) { onProgress = null; }
  70168. if (onError === void 0) { onError = null; }
  70169. if (pluginExtension === void 0) { pluginExtension = null; }
  70170. if (!scene) {
  70171. BABYLON.Tools.Error("No scene available to append to");
  70172. return null;
  70173. }
  70174. if (!sceneFilename) {
  70175. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70176. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70177. }
  70178. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70179. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70180. return null;
  70181. }
  70182. if (SceneLoader.ShowLoadingScreen) {
  70183. scene.getEngine().displayLoadingUI();
  70184. }
  70185. var loadingToken = {};
  70186. scene._addPendingData(loadingToken);
  70187. var disposeHandler = function () {
  70188. scene._removePendingData(loadingToken);
  70189. scene.getEngine().hideLoadingUI();
  70190. };
  70191. var errorHandler = function (message, exception) {
  70192. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70193. if (onError) {
  70194. onError(scene, errorMessage, exception);
  70195. }
  70196. else {
  70197. BABYLON.Tools.Error(errorMessage);
  70198. // should the exception be thrown?
  70199. }
  70200. disposeHandler();
  70201. };
  70202. var progressHandler = onProgress ? function (event) {
  70203. try {
  70204. onProgress(event);
  70205. }
  70206. catch (e) {
  70207. errorHandler("Error in onProgress callback", e);
  70208. }
  70209. } : undefined;
  70210. var successHandler = function () {
  70211. if (onSuccess) {
  70212. try {
  70213. onSuccess(scene);
  70214. }
  70215. catch (e) {
  70216. errorHandler("Error in onSuccess callback", e);
  70217. }
  70218. }
  70219. scene._removePendingData(loadingToken);
  70220. };
  70221. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70222. if (sceneFilename === "") {
  70223. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70224. }
  70225. if (plugin.load) {
  70226. var syncedPlugin = plugin;
  70227. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  70228. return;
  70229. }
  70230. scene.loadingPluginName = plugin.name;
  70231. successHandler();
  70232. }
  70233. else {
  70234. var asyncedPlugin = plugin;
  70235. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  70236. scene.loadingPluginName = plugin.name;
  70237. successHandler();
  70238. }).catch(function (error) {
  70239. errorHandler(error.message, error);
  70240. });
  70241. }
  70242. if (SceneLoader.ShowLoadingScreen) {
  70243. scene.executeWhenReady(function () {
  70244. scene.getEngine().hideLoadingUI();
  70245. });
  70246. }
  70247. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70248. };
  70249. /**
  70250. * Append a scene
  70251. * @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)
  70252. * @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)
  70253. * @param scene is the instance of BABYLON.Scene to append to
  70254. * @param onProgress a callback with a progress event for each file being loaded
  70255. * @param pluginExtension the extension used to determine the plugin
  70256. * @returns The given scene
  70257. */
  70258. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70259. if (sceneFilename === void 0) { sceneFilename = ""; }
  70260. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70261. if (onProgress === void 0) { onProgress = null; }
  70262. if (pluginExtension === void 0) { pluginExtension = null; }
  70263. return new Promise(function (resolve, reject) {
  70264. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  70265. resolve(scene);
  70266. }, onProgress, function (scene, message, exception) {
  70267. reject(exception || new Error(message));
  70268. }, pluginExtension);
  70269. });
  70270. };
  70271. /**
  70272. * Load a scene into an asset container
  70273. * @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)
  70274. * @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)
  70275. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  70276. * @param onSuccess a callback with the scene when import succeeds
  70277. * @param onProgress a callback with a progress event for each file being loaded
  70278. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70279. * @param pluginExtension the extension used to determine the plugin
  70280. * @returns The loaded plugin
  70281. */
  70282. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70283. if (sceneFilename === void 0) { sceneFilename = ""; }
  70284. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70285. if (onSuccess === void 0) { onSuccess = null; }
  70286. if (onProgress === void 0) { onProgress = null; }
  70287. if (onError === void 0) { onError = null; }
  70288. if (pluginExtension === void 0) { pluginExtension = null; }
  70289. if (!scene) {
  70290. BABYLON.Tools.Error("No scene available to load asset container to");
  70291. return null;
  70292. }
  70293. if (!sceneFilename) {
  70294. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70295. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70296. }
  70297. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70298. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70299. return null;
  70300. }
  70301. var loadingToken = {};
  70302. scene._addPendingData(loadingToken);
  70303. var disposeHandler = function () {
  70304. scene._removePendingData(loadingToken);
  70305. };
  70306. var errorHandler = function (message, exception) {
  70307. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70308. if (onError) {
  70309. onError(scene, errorMessage, exception);
  70310. }
  70311. else {
  70312. BABYLON.Tools.Error(errorMessage);
  70313. // should the exception be thrown?
  70314. }
  70315. disposeHandler();
  70316. };
  70317. var progressHandler = onProgress ? function (event) {
  70318. try {
  70319. onProgress(event);
  70320. }
  70321. catch (e) {
  70322. errorHandler("Error in onProgress callback", e);
  70323. }
  70324. } : undefined;
  70325. var successHandler = function (assets) {
  70326. if (onSuccess) {
  70327. try {
  70328. onSuccess(assets);
  70329. }
  70330. catch (e) {
  70331. errorHandler("Error in onSuccess callback", e);
  70332. }
  70333. }
  70334. scene._removePendingData(loadingToken);
  70335. };
  70336. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70337. if (plugin.loadAssetContainer) {
  70338. var syncedPlugin = plugin;
  70339. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  70340. if (!assetContainer) {
  70341. return;
  70342. }
  70343. scene.loadingPluginName = plugin.name;
  70344. successHandler(assetContainer);
  70345. }
  70346. else if (plugin.loadAssetContainerAsync) {
  70347. var asyncedPlugin = plugin;
  70348. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  70349. scene.loadingPluginName = plugin.name;
  70350. successHandler(assetContainer);
  70351. }).catch(function (error) {
  70352. errorHandler(error.message, error);
  70353. });
  70354. }
  70355. else {
  70356. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  70357. }
  70358. if (SceneLoader.ShowLoadingScreen) {
  70359. scene.executeWhenReady(function () {
  70360. scene.getEngine().hideLoadingUI();
  70361. });
  70362. }
  70363. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70364. };
  70365. /**
  70366. * Load a scene into an asset container
  70367. * @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)
  70368. * @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)
  70369. * @param scene is the instance of BABYLON.Scene to append to
  70370. * @param onProgress a callback with a progress event for each file being loaded
  70371. * @param pluginExtension the extension used to determine the plugin
  70372. * @returns The loaded asset container
  70373. */
  70374. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70375. if (sceneFilename === void 0) { sceneFilename = ""; }
  70376. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70377. if (onProgress === void 0) { onProgress = null; }
  70378. if (pluginExtension === void 0) { pluginExtension = null; }
  70379. return new Promise(function (resolve, reject) {
  70380. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  70381. resolve(assetContainer);
  70382. }, onProgress, function (scene, message, exception) {
  70383. reject(exception || new Error(message));
  70384. }, pluginExtension);
  70385. });
  70386. };
  70387. // Flags
  70388. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  70389. SceneLoader._ShowLoadingScreen = true;
  70390. SceneLoader._CleanBoneMatrixWeights = false;
  70391. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  70392. // Members
  70393. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  70394. SceneLoader._registeredPlugins = {};
  70395. return SceneLoader;
  70396. }());
  70397. BABYLON.SceneLoader = SceneLoader;
  70398. ;
  70399. })(BABYLON || (BABYLON = {}));
  70400. //# sourceMappingURL=babylon.sceneLoader.js.map
  70401. var BABYLON;
  70402. (function (BABYLON) {
  70403. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  70404. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70405. var parsedMaterial = parsedData.materials[index];
  70406. if (parsedMaterial.id === id) {
  70407. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70408. }
  70409. }
  70410. return null;
  70411. };
  70412. var isDescendantOf = function (mesh, names, hierarchyIds) {
  70413. for (var i in names) {
  70414. if (mesh.name === names[i]) {
  70415. hierarchyIds.push(mesh.id);
  70416. return true;
  70417. }
  70418. }
  70419. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  70420. hierarchyIds.push(mesh.id);
  70421. return true;
  70422. }
  70423. return false;
  70424. };
  70425. var logOperation = function (operation, producer) {
  70426. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  70427. };
  70428. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  70429. if (addToScene === void 0) { addToScene = false; }
  70430. var container = new BABYLON.AssetContainer(scene);
  70431. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70432. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70433. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70434. // and avoid problems with multiple concurrent .babylon loads.
  70435. var log = "importScene has failed JSON parse";
  70436. try {
  70437. var parsedData = JSON.parse(data);
  70438. log = "";
  70439. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70440. var index;
  70441. var cache;
  70442. // Lights
  70443. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  70444. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  70445. var parsedLight = parsedData.lights[index];
  70446. var light = BABYLON.Light.Parse(parsedLight, scene);
  70447. if (light) {
  70448. container.lights.push(light);
  70449. log += (index === 0 ? "\n\tLights:" : "");
  70450. log += "\n\t\t" + light.toString(fullDetails);
  70451. }
  70452. }
  70453. }
  70454. // Animations
  70455. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  70456. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  70457. var parsedAnimation = parsedData.animations[index];
  70458. var animation = BABYLON.Animation.Parse(parsedAnimation);
  70459. scene.animations.push(animation);
  70460. container.animations.push(animation);
  70461. log += (index === 0 ? "\n\tAnimations:" : "");
  70462. log += "\n\t\t" + animation.toString(fullDetails);
  70463. }
  70464. }
  70465. // Materials
  70466. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  70467. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70468. var parsedMaterial = parsedData.materials[index];
  70469. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70470. container.materials.push(mat);
  70471. log += (index === 0 ? "\n\tMaterials:" : "");
  70472. log += "\n\t\t" + mat.toString(fullDetails);
  70473. }
  70474. }
  70475. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  70476. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  70477. var parsedMultiMaterial = parsedData.multiMaterials[index];
  70478. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  70479. container.multiMaterials.push(mmat);
  70480. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  70481. log += "\n\t\t" + mmat.toString(fullDetails);
  70482. }
  70483. }
  70484. // Morph targets
  70485. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70486. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70487. var managerData = _a[_i];
  70488. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  70489. }
  70490. }
  70491. // Skeletons
  70492. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70493. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  70494. var parsedSkeleton = parsedData.skeletons[index];
  70495. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70496. container.skeletons.push(skeleton);
  70497. log += (index === 0 ? "\n\tSkeletons:" : "");
  70498. log += "\n\t\t" + skeleton.toString(fullDetails);
  70499. }
  70500. }
  70501. // Geometries
  70502. var geometries = parsedData.geometries;
  70503. if (geometries !== undefined && geometries !== null) {
  70504. var addedGeometry = new Array();
  70505. // Boxes
  70506. var boxes = geometries.boxes;
  70507. if (boxes !== undefined && boxes !== null) {
  70508. for (index = 0, cache = boxes.length; index < cache; index++) {
  70509. var parsedBox = boxes[index];
  70510. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  70511. }
  70512. }
  70513. // Spheres
  70514. var spheres = geometries.spheres;
  70515. if (spheres !== undefined && spheres !== null) {
  70516. for (index = 0, cache = spheres.length; index < cache; index++) {
  70517. var parsedSphere = spheres[index];
  70518. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  70519. }
  70520. }
  70521. // Cylinders
  70522. var cylinders = geometries.cylinders;
  70523. if (cylinders !== undefined && cylinders !== null) {
  70524. for (index = 0, cache = cylinders.length; index < cache; index++) {
  70525. var parsedCylinder = cylinders[index];
  70526. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  70527. }
  70528. }
  70529. // Toruses
  70530. var toruses = geometries.toruses;
  70531. if (toruses !== undefined && toruses !== null) {
  70532. for (index = 0, cache = toruses.length; index < cache; index++) {
  70533. var parsedTorus = toruses[index];
  70534. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  70535. }
  70536. }
  70537. // Grounds
  70538. var grounds = geometries.grounds;
  70539. if (grounds !== undefined && grounds !== null) {
  70540. for (index = 0, cache = grounds.length; index < cache; index++) {
  70541. var parsedGround = grounds[index];
  70542. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  70543. }
  70544. }
  70545. // Planes
  70546. var planes = geometries.planes;
  70547. if (planes !== undefined && planes !== null) {
  70548. for (index = 0, cache = planes.length; index < cache; index++) {
  70549. var parsedPlane = planes[index];
  70550. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  70551. }
  70552. }
  70553. // TorusKnots
  70554. var torusKnots = geometries.torusKnots;
  70555. if (torusKnots !== undefined && torusKnots !== null) {
  70556. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  70557. var parsedTorusKnot = torusKnots[index];
  70558. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  70559. }
  70560. }
  70561. // VertexData
  70562. var vertexData = geometries.vertexData;
  70563. if (vertexData !== undefined && vertexData !== null) {
  70564. for (index = 0, cache = vertexData.length; index < cache; index++) {
  70565. var parsedVertexData = vertexData[index];
  70566. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  70567. }
  70568. }
  70569. addedGeometry.forEach(function (g) {
  70570. if (g) {
  70571. container.geometries.push(g);
  70572. }
  70573. });
  70574. }
  70575. // Transform nodes
  70576. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  70577. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  70578. var parsedTransformNode = parsedData.transformNodes[index];
  70579. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  70580. container.transformNodes.push(node);
  70581. }
  70582. }
  70583. // Meshes
  70584. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  70585. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  70586. var parsedMesh = parsedData.meshes[index];
  70587. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70588. container.meshes.push(mesh);
  70589. log += (index === 0 ? "\n\tMeshes:" : "");
  70590. log += "\n\t\t" + mesh.toString(fullDetails);
  70591. }
  70592. }
  70593. // Cameras
  70594. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  70595. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  70596. var parsedCamera = parsedData.cameras[index];
  70597. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  70598. container.cameras.push(camera);
  70599. log += (index === 0 ? "\n\tCameras:" : "");
  70600. log += "\n\t\t" + camera.toString(fullDetails);
  70601. }
  70602. }
  70603. // Browsing all the graph to connect the dots
  70604. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  70605. var camera = scene.cameras[index];
  70606. if (camera._waitingParentId) {
  70607. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  70608. camera._waitingParentId = null;
  70609. }
  70610. }
  70611. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70612. var light_1 = scene.lights[index];
  70613. if (light_1 && light_1._waitingParentId) {
  70614. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  70615. light_1._waitingParentId = null;
  70616. }
  70617. }
  70618. // Sounds
  70619. // TODO: add sound
  70620. var loadedSounds = [];
  70621. var loadedSound;
  70622. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70623. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70624. var parsedSound = parsedData.sounds[index];
  70625. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70626. if (!parsedSound.url)
  70627. parsedSound.url = parsedSound.name;
  70628. if (!loadedSounds[parsedSound.url]) {
  70629. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70630. loadedSounds[parsedSound.url] = loadedSound;
  70631. container.sounds.push(loadedSound);
  70632. }
  70633. else {
  70634. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70635. }
  70636. }
  70637. else {
  70638. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70639. }
  70640. }
  70641. }
  70642. loadedSounds = [];
  70643. // Connect parents & children and parse actions
  70644. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  70645. var transformNode = scene.transformNodes[index];
  70646. if (transformNode._waitingParentId) {
  70647. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  70648. transformNode._waitingParentId = null;
  70649. }
  70650. }
  70651. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70652. var mesh = scene.meshes[index];
  70653. if (mesh._waitingParentId) {
  70654. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  70655. mesh._waitingParentId = null;
  70656. }
  70657. if (mesh._waitingActions) {
  70658. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  70659. mesh._waitingActions = null;
  70660. }
  70661. }
  70662. // freeze world matrix application
  70663. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70664. var currentMesh = scene.meshes[index];
  70665. if (currentMesh._waitingFreezeWorldMatrix) {
  70666. currentMesh.freezeWorldMatrix();
  70667. currentMesh._waitingFreezeWorldMatrix = null;
  70668. }
  70669. else {
  70670. currentMesh.computeWorldMatrix(true);
  70671. }
  70672. }
  70673. // Shadows
  70674. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  70675. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  70676. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  70677. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  70678. // SG would be available on their associated lights
  70679. }
  70680. }
  70681. // Lights exclusions / inclusions
  70682. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70683. var light_2 = scene.lights[index];
  70684. // Excluded check
  70685. if (light_2._excludedMeshesIds.length > 0) {
  70686. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  70687. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  70688. if (excludedMesh) {
  70689. light_2.excludedMeshes.push(excludedMesh);
  70690. }
  70691. }
  70692. light_2._excludedMeshesIds = [];
  70693. }
  70694. // Included check
  70695. if (light_2._includedOnlyMeshesIds.length > 0) {
  70696. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  70697. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  70698. if (includedOnlyMesh) {
  70699. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  70700. }
  70701. }
  70702. light_2._includedOnlyMeshesIds = [];
  70703. }
  70704. }
  70705. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  70706. // Actions (scene)
  70707. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  70708. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  70709. }
  70710. if (!addToScene) {
  70711. container.removeAllFromScene();
  70712. }
  70713. }
  70714. catch (err) {
  70715. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  70716. if (onError) {
  70717. onError(msg, err);
  70718. }
  70719. else {
  70720. BABYLON.Tools.Log(msg);
  70721. throw err;
  70722. }
  70723. }
  70724. finally {
  70725. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70726. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70727. }
  70728. }
  70729. return container;
  70730. };
  70731. BABYLON.SceneLoader.RegisterPlugin({
  70732. name: "babylon.js",
  70733. extensions: ".babylon",
  70734. canDirectLoad: function (data) {
  70735. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  70736. return true;
  70737. }
  70738. return false;
  70739. },
  70740. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  70741. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70742. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70743. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70744. // and avoid problems with multiple concurrent .babylon loads.
  70745. var log = "importMesh has failed JSON parse";
  70746. try {
  70747. var parsedData = JSON.parse(data);
  70748. log = "";
  70749. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70750. if (!meshesNames) {
  70751. meshesNames = null;
  70752. }
  70753. else if (!Array.isArray(meshesNames)) {
  70754. meshesNames = [meshesNames];
  70755. }
  70756. var hierarchyIds = new Array();
  70757. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  70758. var loadedSkeletonsIds = [];
  70759. var loadedMaterialsIds = [];
  70760. var index;
  70761. var cache;
  70762. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  70763. var parsedMesh = parsedData.meshes[index];
  70764. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  70765. if (meshesNames !== null) {
  70766. // Remove found mesh name from list.
  70767. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  70768. }
  70769. //Geometry?
  70770. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  70771. //does the file contain geometries?
  70772. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  70773. //find the correct geometry and add it to the scene
  70774. var found = false;
  70775. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  70776. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  70777. return;
  70778. }
  70779. else {
  70780. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  70781. if (parsedGeometryData.id === parsedMesh.geometryId) {
  70782. switch (geometryType) {
  70783. case "boxes":
  70784. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  70785. break;
  70786. case "spheres":
  70787. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  70788. break;
  70789. case "cylinders":
  70790. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  70791. break;
  70792. case "toruses":
  70793. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  70794. break;
  70795. case "grounds":
  70796. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  70797. break;
  70798. case "planes":
  70799. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  70800. break;
  70801. case "torusKnots":
  70802. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  70803. break;
  70804. case "vertexData":
  70805. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  70806. break;
  70807. }
  70808. found = true;
  70809. }
  70810. });
  70811. }
  70812. });
  70813. if (found === false) {
  70814. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  70815. }
  70816. }
  70817. }
  70818. // Material ?
  70819. if (parsedMesh.materialId) {
  70820. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  70821. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  70822. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  70823. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  70824. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  70825. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  70826. var subMatId = parsedMultiMaterial.materials[matIndex];
  70827. loadedMaterialsIds.push(subMatId);
  70828. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  70829. if (mat) {
  70830. log += "\n\tMaterial " + mat.toString(fullDetails);
  70831. }
  70832. }
  70833. loadedMaterialsIds.push(parsedMultiMaterial.id);
  70834. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  70835. if (mmat) {
  70836. materialFound = true;
  70837. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  70838. }
  70839. break;
  70840. }
  70841. }
  70842. }
  70843. if (materialFound === false) {
  70844. loadedMaterialsIds.push(parsedMesh.materialId);
  70845. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  70846. if (!mat) {
  70847. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  70848. }
  70849. else {
  70850. log += "\n\tMaterial " + mat.toString(fullDetails);
  70851. }
  70852. }
  70853. }
  70854. // Skeleton ?
  70855. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70856. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  70857. if (skeletonAlreadyLoaded === false) {
  70858. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  70859. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  70860. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  70861. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70862. skeletons.push(skeleton);
  70863. loadedSkeletonsIds.push(parsedSkeleton.id);
  70864. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  70865. }
  70866. }
  70867. }
  70868. }
  70869. // Morph targets ?
  70870. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70871. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70872. var managerData = _a[_i];
  70873. BABYLON.MorphTargetManager.Parse(managerData, scene);
  70874. }
  70875. }
  70876. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70877. meshes.push(mesh);
  70878. log += "\n\tMesh " + mesh.toString(fullDetails);
  70879. }
  70880. }
  70881. // Connecting parents
  70882. var currentMesh;
  70883. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70884. currentMesh = scene.meshes[index];
  70885. if (currentMesh._waitingParentId) {
  70886. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  70887. currentMesh._waitingParentId = null;
  70888. }
  70889. }
  70890. // freeze and compute world matrix application
  70891. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70892. currentMesh = scene.meshes[index];
  70893. if (currentMesh._waitingFreezeWorldMatrix) {
  70894. currentMesh.freezeWorldMatrix();
  70895. currentMesh._waitingFreezeWorldMatrix = null;
  70896. }
  70897. else {
  70898. currentMesh.computeWorldMatrix(true);
  70899. }
  70900. }
  70901. }
  70902. // Particles
  70903. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  70904. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  70905. if (parser) {
  70906. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  70907. var parsedParticleSystem = parsedData.particleSystems[index];
  70908. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  70909. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  70910. }
  70911. }
  70912. }
  70913. }
  70914. return true;
  70915. }
  70916. catch (err) {
  70917. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  70918. if (onError) {
  70919. onError(msg, err);
  70920. }
  70921. else {
  70922. BABYLON.Tools.Log(msg);
  70923. throw err;
  70924. }
  70925. }
  70926. finally {
  70927. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70928. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70929. }
  70930. }
  70931. return false;
  70932. },
  70933. load: function (scene, data, rootUrl, onError) {
  70934. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70935. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70936. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70937. // and avoid problems with multiple concurrent .babylon loads.
  70938. var log = "importScene has failed JSON parse";
  70939. try {
  70940. var parsedData = JSON.parse(data);
  70941. log = "";
  70942. // Scene
  70943. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  70944. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  70945. }
  70946. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  70947. scene.autoClear = parsedData.autoClear;
  70948. }
  70949. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  70950. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  70951. }
  70952. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  70953. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  70954. }
  70955. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  70956. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  70957. }
  70958. // Fog
  70959. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  70960. scene.fogMode = parsedData.fogMode;
  70961. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  70962. scene.fogStart = parsedData.fogStart;
  70963. scene.fogEnd = parsedData.fogEnd;
  70964. scene.fogDensity = parsedData.fogDensity;
  70965. log += "\tFog mode for scene: ";
  70966. switch (scene.fogMode) {
  70967. // getters not compiling, so using hardcoded
  70968. case 1:
  70969. log += "exp\n";
  70970. break;
  70971. case 2:
  70972. log += "exp2\n";
  70973. break;
  70974. case 3:
  70975. log += "linear\n";
  70976. break;
  70977. }
  70978. }
  70979. //Physics
  70980. if (parsedData.physicsEnabled) {
  70981. var physicsPlugin;
  70982. if (parsedData.physicsEngine === "cannon") {
  70983. physicsPlugin = new BABYLON.CannonJSPlugin();
  70984. }
  70985. else if (parsedData.physicsEngine === "oimo") {
  70986. physicsPlugin = new BABYLON.OimoJSPlugin();
  70987. }
  70988. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  70989. //else - default engine, which is currently oimo
  70990. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  70991. scene.enablePhysics(physicsGravity, physicsPlugin);
  70992. }
  70993. // Metadata
  70994. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  70995. scene.metadata = parsedData.metadata;
  70996. }
  70997. //collisions, if defined. otherwise, default is true
  70998. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  70999. scene.collisionsEnabled = parsedData.collisionsEnabled;
  71000. }
  71001. scene.workerCollisions = !!parsedData.workerCollisions;
  71002. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  71003. if (!container) {
  71004. return false;
  71005. }
  71006. if (parsedData.autoAnimate) {
  71007. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  71008. }
  71009. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  71010. scene.setActiveCameraByID(parsedData.activeCameraID);
  71011. }
  71012. // Environment texture
  71013. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  71014. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  71015. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  71016. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  71017. if (parsedData.environmentTextureRotationY) {
  71018. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  71019. }
  71020. scene.environmentTexture = hdrTexture;
  71021. }
  71022. else {
  71023. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  71024. if (parsedData.environmentTextureRotationY) {
  71025. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  71026. }
  71027. scene.environmentTexture = cubeTexture;
  71028. }
  71029. if (parsedData.createDefaultSkybox === true) {
  71030. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  71031. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  71032. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  71033. }
  71034. }
  71035. // Finish
  71036. return true;
  71037. }
  71038. catch (err) {
  71039. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  71040. if (onError) {
  71041. onError(msg, err);
  71042. }
  71043. else {
  71044. BABYLON.Tools.Log(msg);
  71045. throw err;
  71046. }
  71047. }
  71048. finally {
  71049. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71050. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71051. }
  71052. }
  71053. return false;
  71054. },
  71055. loadAssetContainer: function (scene, data, rootUrl, onError) {
  71056. var container = loadAssetContainer(scene, data, rootUrl, onError);
  71057. return container;
  71058. }
  71059. });
  71060. })(BABYLON || (BABYLON = {}));
  71061. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  71062. var BABYLON;
  71063. (function (BABYLON) {
  71064. var FilesInput = /** @class */ (function () {
  71065. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  71066. this.onProcessFileCallback = function () { return true; };
  71067. this._engine = engine;
  71068. this._currentScene = scene;
  71069. this._sceneLoadedCallback = sceneLoadedCallback;
  71070. this._progressCallback = progressCallback;
  71071. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  71072. this._textureLoadingCallback = textureLoadingCallback;
  71073. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  71074. this._onReloadCallback = onReloadCallback;
  71075. this._errorCallback = errorCallback;
  71076. }
  71077. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  71078. var _this = this;
  71079. if (elementToMonitor) {
  71080. this._elementToMonitor = elementToMonitor;
  71081. this._dragEnterHandler = function (e) { _this.drag(e); };
  71082. this._dragOverHandler = function (e) { _this.drag(e); };
  71083. this._dropHandler = function (e) { _this.drop(e); };
  71084. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  71085. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  71086. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  71087. }
  71088. };
  71089. FilesInput.prototype.dispose = function () {
  71090. if (!this._elementToMonitor) {
  71091. return;
  71092. }
  71093. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  71094. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  71095. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  71096. };
  71097. FilesInput.prototype.renderFunction = function () {
  71098. if (this._additionalRenderLoopLogicCallback) {
  71099. this._additionalRenderLoopLogicCallback();
  71100. }
  71101. if (this._currentScene) {
  71102. if (this._textureLoadingCallback) {
  71103. var remaining = this._currentScene.getWaitingItemsCount();
  71104. if (remaining > 0) {
  71105. this._textureLoadingCallback(remaining);
  71106. }
  71107. }
  71108. this._currentScene.render();
  71109. }
  71110. };
  71111. FilesInput.prototype.drag = function (e) {
  71112. e.stopPropagation();
  71113. e.preventDefault();
  71114. };
  71115. FilesInput.prototype.drop = function (eventDrop) {
  71116. eventDrop.stopPropagation();
  71117. eventDrop.preventDefault();
  71118. this.loadFiles(eventDrop);
  71119. };
  71120. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  71121. var _this = this;
  71122. var reader = folder.createReader();
  71123. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  71124. reader.readEntries(function (entries) {
  71125. remaining.count += entries.length;
  71126. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  71127. var entry = entries_1[_i];
  71128. if (entry.isFile) {
  71129. entry.file(function (file) {
  71130. file.correctName = relativePath + file.name;
  71131. files.push(file);
  71132. if (--remaining.count === 0) {
  71133. callback();
  71134. }
  71135. });
  71136. }
  71137. else if (entry.isDirectory) {
  71138. _this._traverseFolder(entry, files, remaining, callback);
  71139. }
  71140. }
  71141. if (--remaining.count) {
  71142. callback();
  71143. }
  71144. });
  71145. };
  71146. FilesInput.prototype._processFiles = function (files) {
  71147. for (var i = 0; i < files.length; i++) {
  71148. var name = files[i].correctName.toLowerCase();
  71149. var extension = name.split('.').pop();
  71150. if (!this.onProcessFileCallback(files[i], name, extension)) {
  71151. continue;
  71152. }
  71153. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  71154. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  71155. this._sceneFileToLoad = files[i];
  71156. }
  71157. else {
  71158. FilesInput.FilesToLoad[name] = files[i];
  71159. }
  71160. }
  71161. };
  71162. FilesInput.prototype.loadFiles = function (event) {
  71163. var _this = this;
  71164. if (this._startingProcessingFilesCallback)
  71165. this._startingProcessingFilesCallback();
  71166. // Handling data transfer via drag'n'drop
  71167. if (event && event.dataTransfer && event.dataTransfer.files) {
  71168. this._filesToLoad = event.dataTransfer.files;
  71169. }
  71170. // Handling files from input files
  71171. if (event && event.target && event.target.files) {
  71172. this._filesToLoad = event.target.files;
  71173. }
  71174. if (this._filesToLoad && this._filesToLoad.length > 0) {
  71175. var files_1 = new Array();
  71176. var folders = [];
  71177. var items = event.dataTransfer ? event.dataTransfer.items : null;
  71178. for (var i = 0; i < this._filesToLoad.length; i++) {
  71179. var fileToLoad = this._filesToLoad[i];
  71180. var name_1 = fileToLoad.name.toLowerCase();
  71181. var entry = void 0;
  71182. fileToLoad.correctName = name_1;
  71183. if (items) {
  71184. var item = items[i];
  71185. if (item.getAsEntry) {
  71186. entry = item.getAsEntry();
  71187. }
  71188. else if (item.webkitGetAsEntry) {
  71189. entry = item.webkitGetAsEntry();
  71190. }
  71191. }
  71192. if (!entry) {
  71193. files_1.push(fileToLoad);
  71194. }
  71195. else {
  71196. if (entry.isDirectory) {
  71197. folders.push(entry);
  71198. }
  71199. else {
  71200. files_1.push(fileToLoad);
  71201. }
  71202. }
  71203. }
  71204. if (folders.length === 0) {
  71205. this._processFiles(files_1);
  71206. this._processReload();
  71207. }
  71208. else {
  71209. var remaining = { count: folders.length };
  71210. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  71211. var folder = folders_1[_i];
  71212. this._traverseFolder(folder, files_1, remaining, function () {
  71213. _this._processFiles(files_1);
  71214. if (remaining.count === 0) {
  71215. _this._processReload();
  71216. }
  71217. });
  71218. }
  71219. }
  71220. }
  71221. };
  71222. FilesInput.prototype._processReload = function () {
  71223. if (this._onReloadCallback) {
  71224. this._onReloadCallback(this._sceneFileToLoad);
  71225. }
  71226. else {
  71227. this.reload();
  71228. }
  71229. };
  71230. FilesInput.prototype.reload = function () {
  71231. var _this = this;
  71232. // If a scene file has been provided
  71233. if (this._sceneFileToLoad) {
  71234. if (this._currentScene) {
  71235. if (BABYLON.Tools.errorsCount > 0) {
  71236. BABYLON.Tools.ClearLogCache();
  71237. }
  71238. this._engine.stopRenderLoop();
  71239. }
  71240. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  71241. if (_this._progressCallback) {
  71242. _this._progressCallback(progress);
  71243. }
  71244. }).then(function (scene) {
  71245. if (_this._currentScene) {
  71246. _this._currentScene.dispose();
  71247. }
  71248. _this._currentScene = scene;
  71249. if (_this._sceneLoadedCallback) {
  71250. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  71251. }
  71252. // Wait for textures and shaders to be ready
  71253. _this._currentScene.executeWhenReady(function () {
  71254. _this._engine.runRenderLoop(function () {
  71255. _this.renderFunction();
  71256. });
  71257. });
  71258. }).catch(function (error) {
  71259. if (_this._errorCallback) {
  71260. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  71261. }
  71262. });
  71263. }
  71264. else {
  71265. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  71266. }
  71267. };
  71268. FilesInput.FilesToLoad = {};
  71269. return FilesInput;
  71270. }());
  71271. BABYLON.FilesInput = FilesInput;
  71272. })(BABYLON || (BABYLON = {}));
  71273. //# sourceMappingURL=babylon.filesInput.js.map
  71274. var BABYLON;
  71275. (function (BABYLON) {
  71276. var Tags = /** @class */ (function () {
  71277. function Tags() {
  71278. }
  71279. Tags.EnableFor = function (obj) {
  71280. obj._tags = obj._tags || {};
  71281. obj.hasTags = function () {
  71282. return Tags.HasTags(obj);
  71283. };
  71284. obj.addTags = function (tagsString) {
  71285. return Tags.AddTagsTo(obj, tagsString);
  71286. };
  71287. obj.removeTags = function (tagsString) {
  71288. return Tags.RemoveTagsFrom(obj, tagsString);
  71289. };
  71290. obj.matchesTagsQuery = function (tagsQuery) {
  71291. return Tags.MatchesQuery(obj, tagsQuery);
  71292. };
  71293. };
  71294. Tags.DisableFor = function (obj) {
  71295. delete obj._tags;
  71296. delete obj.hasTags;
  71297. delete obj.addTags;
  71298. delete obj.removeTags;
  71299. delete obj.matchesTagsQuery;
  71300. };
  71301. Tags.HasTags = function (obj) {
  71302. if (!obj._tags) {
  71303. return false;
  71304. }
  71305. return !BABYLON.Tools.IsEmpty(obj._tags);
  71306. };
  71307. Tags.GetTags = function (obj, asString) {
  71308. if (asString === void 0) { asString = true; }
  71309. if (!obj._tags) {
  71310. return null;
  71311. }
  71312. if (asString) {
  71313. var tagsArray = [];
  71314. for (var tag in obj._tags) {
  71315. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  71316. tagsArray.push(tag);
  71317. }
  71318. }
  71319. return tagsArray.join(" ");
  71320. }
  71321. else {
  71322. return obj._tags;
  71323. }
  71324. };
  71325. // the tags 'true' and 'false' are reserved and cannot be used as tags
  71326. // a tag cannot start with '||', '&&', and '!'
  71327. // it cannot contain whitespaces
  71328. Tags.AddTagsTo = function (obj, tagsString) {
  71329. if (!tagsString) {
  71330. return;
  71331. }
  71332. if (typeof tagsString !== "string") {
  71333. return;
  71334. }
  71335. var tags = tagsString.split(" ");
  71336. tags.forEach(function (tag, index, array) {
  71337. Tags._AddTagTo(obj, tag);
  71338. });
  71339. };
  71340. Tags._AddTagTo = function (obj, tag) {
  71341. tag = tag.trim();
  71342. if (tag === "" || tag === "true" || tag === "false") {
  71343. return;
  71344. }
  71345. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  71346. return;
  71347. }
  71348. Tags.EnableFor(obj);
  71349. obj._tags[tag] = true;
  71350. };
  71351. Tags.RemoveTagsFrom = function (obj, tagsString) {
  71352. if (!Tags.HasTags(obj)) {
  71353. return;
  71354. }
  71355. var tags = tagsString.split(" ");
  71356. for (var t in tags) {
  71357. Tags._RemoveTagFrom(obj, tags[t]);
  71358. }
  71359. };
  71360. Tags._RemoveTagFrom = function (obj, tag) {
  71361. delete obj._tags[tag];
  71362. };
  71363. Tags.MatchesQuery = function (obj, tagsQuery) {
  71364. if (tagsQuery === undefined) {
  71365. return true;
  71366. }
  71367. if (tagsQuery === "") {
  71368. return Tags.HasTags(obj);
  71369. }
  71370. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  71371. };
  71372. return Tags;
  71373. }());
  71374. BABYLON.Tags = Tags;
  71375. })(BABYLON || (BABYLON = {}));
  71376. //# sourceMappingURL=babylon.tags.js.map
  71377. var BABYLON;
  71378. (function (BABYLON) {
  71379. /**
  71380. * Class used to evalaute queries containing `and` and `or` operators
  71381. */
  71382. var AndOrNotEvaluator = /** @class */ (function () {
  71383. function AndOrNotEvaluator() {
  71384. }
  71385. /**
  71386. * Evaluate a query
  71387. * @param query defines the query to evaluate
  71388. * @param evaluateCallback defines the callback used to filter result
  71389. * @returns true if the query matches
  71390. */
  71391. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  71392. if (!query.match(/\([^\(\)]*\)/g)) {
  71393. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  71394. }
  71395. else {
  71396. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  71397. // remove parenthesis
  71398. r = r.slice(1, r.length - 1);
  71399. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  71400. });
  71401. }
  71402. if (query === "true") {
  71403. return true;
  71404. }
  71405. if (query === "false") {
  71406. return false;
  71407. }
  71408. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  71409. };
  71410. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  71411. evaluateCallback = evaluateCallback || (function (r) {
  71412. return r === "true" ? true : false;
  71413. });
  71414. var result;
  71415. var or = parenthesisContent.split("||");
  71416. for (var i in or) {
  71417. if (or.hasOwnProperty(i)) {
  71418. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  71419. var and = ori.split("&&");
  71420. if (and.length > 1) {
  71421. for (var j = 0; j < and.length; ++j) {
  71422. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  71423. if (andj !== "true" && andj !== "false") {
  71424. if (andj[0] === "!") {
  71425. result = !evaluateCallback(andj.substring(1));
  71426. }
  71427. else {
  71428. result = evaluateCallback(andj);
  71429. }
  71430. }
  71431. else {
  71432. result = andj === "true" ? true : false;
  71433. }
  71434. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  71435. ori = "false";
  71436. break;
  71437. }
  71438. }
  71439. }
  71440. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  71441. result = true;
  71442. break;
  71443. }
  71444. // result equals false (or undefined)
  71445. if (ori !== "true" && ori !== "false") {
  71446. if (ori[0] === "!") {
  71447. result = !evaluateCallback(ori.substring(1));
  71448. }
  71449. else {
  71450. result = evaluateCallback(ori);
  71451. }
  71452. }
  71453. else {
  71454. result = ori === "true" ? true : false;
  71455. }
  71456. }
  71457. }
  71458. // the whole parenthesis scope is replaced by 'true' or 'false'
  71459. return result ? "true" : "false";
  71460. };
  71461. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  71462. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  71463. // remove whitespaces
  71464. r = r.replace(/[\s]/g, function () { return ""; });
  71465. return r.length % 2 ? "!" : "";
  71466. });
  71467. booleanString = booleanString.trim();
  71468. if (booleanString === "!true") {
  71469. booleanString = "false";
  71470. }
  71471. else if (booleanString === "!false") {
  71472. booleanString = "true";
  71473. }
  71474. return booleanString;
  71475. };
  71476. return AndOrNotEvaluator;
  71477. }());
  71478. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  71479. })(BABYLON || (BABYLON = {}));
  71480. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  71481. var BABYLON;
  71482. (function (BABYLON) {
  71483. /**
  71484. * Class used to enable access to IndexedDB
  71485. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  71486. */
  71487. var Database = /** @class */ (function () {
  71488. /**
  71489. * Creates a new Database
  71490. * @param urlToScene defines the url to load the scene
  71491. * @param callbackManifestChecked defines the callback to use when manifest is checked
  71492. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  71493. */
  71494. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  71495. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  71496. var _this = this;
  71497. // Handling various flavors of prefixed version of IndexedDB
  71498. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  71499. this.callbackManifestChecked = callbackManifestChecked;
  71500. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  71501. this.db = null;
  71502. this._enableSceneOffline = false;
  71503. this._enableTexturesOffline = false;
  71504. this.manifestVersionFound = 0;
  71505. this.mustUpdateRessources = false;
  71506. this.hasReachedQuota = false;
  71507. if (!Database.IDBStorageEnabled) {
  71508. this.callbackManifestChecked(true);
  71509. }
  71510. else {
  71511. if (disableManifestCheck) {
  71512. this._enableSceneOffline = true;
  71513. this._enableTexturesOffline = true;
  71514. this.manifestVersionFound = 1;
  71515. BABYLON.Tools.SetImmediate(function () {
  71516. _this.callbackManifestChecked(true);
  71517. });
  71518. }
  71519. else {
  71520. this._checkManifestFile();
  71521. }
  71522. }
  71523. }
  71524. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  71525. /**
  71526. * Gets a boolean indicating if scene must be saved in the database
  71527. */
  71528. get: function () {
  71529. return this._enableSceneOffline;
  71530. },
  71531. enumerable: true,
  71532. configurable: true
  71533. });
  71534. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  71535. /**
  71536. * Gets a boolean indicating if textures must be saved in the database
  71537. */
  71538. get: function () {
  71539. return this._enableTexturesOffline;
  71540. },
  71541. enumerable: true,
  71542. configurable: true
  71543. });
  71544. Database.prototype._checkManifestFile = function () {
  71545. var _this = this;
  71546. var noManifestFile = function () {
  71547. _this._enableSceneOffline = false;
  71548. _this._enableTexturesOffline = false;
  71549. _this.callbackManifestChecked(false);
  71550. };
  71551. var timeStampUsed = false;
  71552. var manifestURL = this.currentSceneUrl + ".manifest";
  71553. var xhr = new XMLHttpRequest();
  71554. if (navigator.onLine) {
  71555. // Adding a timestamp to by-pass browsers' cache
  71556. timeStampUsed = true;
  71557. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  71558. }
  71559. xhr.open("GET", manifestURL, true);
  71560. xhr.addEventListener("load", function () {
  71561. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71562. try {
  71563. var manifestFile = JSON.parse(xhr.response);
  71564. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  71565. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  71566. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  71567. _this.manifestVersionFound = manifestFile.version;
  71568. }
  71569. if (_this.callbackManifestChecked) {
  71570. _this.callbackManifestChecked(true);
  71571. }
  71572. }
  71573. catch (ex) {
  71574. noManifestFile();
  71575. }
  71576. }
  71577. else {
  71578. noManifestFile();
  71579. }
  71580. }, false);
  71581. xhr.addEventListener("error", function (event) {
  71582. if (timeStampUsed) {
  71583. timeStampUsed = false;
  71584. // Let's retry without the timeStamp
  71585. // It could fail when coupled with HTML5 Offline API
  71586. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  71587. xhr.open("GET", retryManifestURL, true);
  71588. xhr.send();
  71589. }
  71590. else {
  71591. noManifestFile();
  71592. }
  71593. }, false);
  71594. try {
  71595. xhr.send();
  71596. }
  71597. catch (ex) {
  71598. BABYLON.Tools.Error("Error on XHR send request.");
  71599. this.callbackManifestChecked(false);
  71600. }
  71601. };
  71602. /**
  71603. * Open the database and make it available
  71604. * @param successCallback defines the callback to call on success
  71605. * @param errorCallback defines the callback to call on error
  71606. */
  71607. Database.prototype.openAsync = function (successCallback, errorCallback) {
  71608. var _this = this;
  71609. var handleError = function () {
  71610. _this.isSupported = false;
  71611. if (errorCallback)
  71612. errorCallback();
  71613. };
  71614. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  71615. // Your browser doesn't support IndexedDB
  71616. this.isSupported = false;
  71617. if (errorCallback)
  71618. errorCallback();
  71619. }
  71620. else {
  71621. // If the DB hasn't been opened or created yet
  71622. if (!this.db) {
  71623. this.hasReachedQuota = false;
  71624. this.isSupported = true;
  71625. var request = this.idbFactory.open("babylonjs", 1);
  71626. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  71627. request.onerror = function (event) {
  71628. handleError();
  71629. };
  71630. // executes when a version change transaction cannot complete due to other active transactions
  71631. request.onblocked = function (event) {
  71632. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  71633. handleError();
  71634. };
  71635. // DB has been opened successfully
  71636. request.onsuccess = function (event) {
  71637. _this.db = request.result;
  71638. successCallback();
  71639. };
  71640. // Initialization of the DB. Creating Scenes & Textures stores
  71641. request.onupgradeneeded = function (event) {
  71642. _this.db = (event.target).result;
  71643. if (_this.db) {
  71644. try {
  71645. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  71646. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  71647. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  71648. }
  71649. catch (ex) {
  71650. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  71651. handleError();
  71652. }
  71653. }
  71654. };
  71655. }
  71656. // DB has already been created and opened
  71657. else {
  71658. if (successCallback)
  71659. successCallback();
  71660. }
  71661. }
  71662. };
  71663. /**
  71664. * Loads an image from the database
  71665. * @param url defines the url to load from
  71666. * @param image defines the target DOM image
  71667. */
  71668. Database.prototype.loadImageFromDB = function (url, image) {
  71669. var _this = this;
  71670. var completeURL = Database._ReturnFullUrlLocation(url);
  71671. var saveAndLoadImage = function () {
  71672. if (!_this.hasReachedQuota && _this.db !== null) {
  71673. // the texture is not yet in the DB, let's try to save it
  71674. _this._saveImageIntoDBAsync(completeURL, image);
  71675. }
  71676. // If the texture is not in the DB and we've reached the DB quota limit
  71677. // let's load it directly from the web
  71678. else {
  71679. image.src = url;
  71680. }
  71681. };
  71682. if (!this.mustUpdateRessources) {
  71683. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  71684. }
  71685. // First time we're download the images or update requested in the manifest file by a version change
  71686. else {
  71687. saveAndLoadImage();
  71688. }
  71689. };
  71690. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  71691. if (this.isSupported && this.db !== null) {
  71692. var texture;
  71693. var transaction = this.db.transaction(["textures"]);
  71694. transaction.onabort = function (event) {
  71695. image.src = url;
  71696. };
  71697. transaction.oncomplete = function (event) {
  71698. var blobTextureURL;
  71699. if (texture) {
  71700. var URL = window.URL || window.webkitURL;
  71701. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  71702. image.onerror = function () {
  71703. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  71704. image.src = url;
  71705. };
  71706. image.src = blobTextureURL;
  71707. }
  71708. else {
  71709. notInDBCallback();
  71710. }
  71711. };
  71712. var getRequest = transaction.objectStore("textures").get(url);
  71713. getRequest.onsuccess = function (event) {
  71714. texture = (event.target).result;
  71715. };
  71716. getRequest.onerror = function (event) {
  71717. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  71718. image.src = url;
  71719. };
  71720. }
  71721. else {
  71722. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71723. image.src = url;
  71724. }
  71725. };
  71726. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  71727. var _this = this;
  71728. if (this.isSupported) {
  71729. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  71730. var generateBlobUrl = function () {
  71731. var blobTextureURL;
  71732. if (blob) {
  71733. var URL = window.URL || window.webkitURL;
  71734. try {
  71735. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  71736. }
  71737. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  71738. catch (ex) {
  71739. blobTextureURL = URL.createObjectURL(blob);
  71740. }
  71741. }
  71742. if (blobTextureURL) {
  71743. image.src = blobTextureURL;
  71744. }
  71745. };
  71746. if (Database.IsUASupportingBlobStorage) { // Create XHR
  71747. var xhr = new XMLHttpRequest(), blob;
  71748. xhr.open("GET", url, true);
  71749. xhr.responseType = "blob";
  71750. xhr.addEventListener("load", function () {
  71751. if (xhr.status === 200 && _this.db) {
  71752. // Blob as response (XHR2)
  71753. blob = xhr.response;
  71754. var transaction = _this.db.transaction(["textures"], "readwrite");
  71755. // the transaction could abort because of a QuotaExceededError error
  71756. transaction.onabort = function (event) {
  71757. try {
  71758. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71759. var srcElement = (event.srcElement || event.target);
  71760. var error = srcElement.error;
  71761. if (error && error.name === "QuotaExceededError") {
  71762. _this.hasReachedQuota = true;
  71763. }
  71764. }
  71765. catch (ex) { }
  71766. generateBlobUrl();
  71767. };
  71768. transaction.oncomplete = function (event) {
  71769. generateBlobUrl();
  71770. };
  71771. var newTexture = { textureUrl: url, data: blob };
  71772. try {
  71773. // Put the blob into the dabase
  71774. var addRequest = transaction.objectStore("textures").put(newTexture);
  71775. addRequest.onsuccess = function (event) {
  71776. };
  71777. addRequest.onerror = function (event) {
  71778. generateBlobUrl();
  71779. };
  71780. }
  71781. catch (ex) {
  71782. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  71783. if (ex.code === 25) {
  71784. Database.IsUASupportingBlobStorage = false;
  71785. }
  71786. image.src = url;
  71787. }
  71788. }
  71789. else {
  71790. image.src = url;
  71791. }
  71792. }, false);
  71793. xhr.addEventListener("error", function (event) {
  71794. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  71795. image.src = url;
  71796. }, false);
  71797. xhr.send();
  71798. }
  71799. else {
  71800. image.src = url;
  71801. }
  71802. }
  71803. else {
  71804. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71805. image.src = url;
  71806. }
  71807. };
  71808. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  71809. var _this = this;
  71810. var updateVersion = function () {
  71811. // the version is not yet in the DB or we need to update it
  71812. _this._saveVersionIntoDBAsync(url, versionLoaded);
  71813. };
  71814. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  71815. };
  71816. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  71817. var _this = this;
  71818. if (this.isSupported && this.db) {
  71819. var version;
  71820. try {
  71821. var transaction = this.db.transaction(["versions"]);
  71822. transaction.oncomplete = function (event) {
  71823. if (version) {
  71824. // If the version in the JSON file is different from the version in DB
  71825. if (_this.manifestVersionFound !== version.data) {
  71826. _this.mustUpdateRessources = true;
  71827. updateInDBCallback();
  71828. }
  71829. else {
  71830. callback(version.data);
  71831. }
  71832. }
  71833. // version was not found in DB
  71834. else {
  71835. _this.mustUpdateRessources = true;
  71836. updateInDBCallback();
  71837. }
  71838. };
  71839. transaction.onabort = function (event) {
  71840. callback(-1);
  71841. };
  71842. var getRequest = transaction.objectStore("versions").get(url);
  71843. getRequest.onsuccess = function (event) {
  71844. version = (event.target).result;
  71845. };
  71846. getRequest.onerror = function (event) {
  71847. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  71848. callback(-1);
  71849. };
  71850. }
  71851. catch (ex) {
  71852. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  71853. callback(-1);
  71854. }
  71855. }
  71856. else {
  71857. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71858. callback(-1);
  71859. }
  71860. };
  71861. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  71862. var _this = this;
  71863. if (this.isSupported && !this.hasReachedQuota && this.db) {
  71864. try {
  71865. // Open a transaction to the database
  71866. var transaction = this.db.transaction(["versions"], "readwrite");
  71867. // the transaction could abort because of a QuotaExceededError error
  71868. transaction.onabort = function (event) {
  71869. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71870. var error = event.srcElement['error'];
  71871. if (error && error.name === "QuotaExceededError") {
  71872. _this.hasReachedQuota = true;
  71873. }
  71874. }
  71875. catch (ex) { }
  71876. callback(-1);
  71877. };
  71878. transaction.oncomplete = function (event) {
  71879. callback(_this.manifestVersionFound);
  71880. };
  71881. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  71882. // Put the scene into the database
  71883. var addRequest = transaction.objectStore("versions").put(newVersion);
  71884. addRequest.onsuccess = function (event) {
  71885. };
  71886. addRequest.onerror = function (event) {
  71887. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  71888. };
  71889. }
  71890. catch (ex) {
  71891. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  71892. callback(-1);
  71893. }
  71894. }
  71895. else {
  71896. callback(-1);
  71897. }
  71898. };
  71899. /**
  71900. * Loads a file from database
  71901. * @param url defines the URL to load from
  71902. * @param sceneLoaded defines a callback to call on success
  71903. * @param progressCallBack defines a callback to call when progress changed
  71904. * @param errorCallback defines a callback to call on error
  71905. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  71906. */
  71907. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  71908. var _this = this;
  71909. var completeUrl = Database._ReturnFullUrlLocation(url);
  71910. var saveAndLoadFile = function () {
  71911. // the scene is not yet in the DB, let's try to save it
  71912. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  71913. };
  71914. this._checkVersionFromDB(completeUrl, function (version) {
  71915. if (version !== -1) {
  71916. if (!_this.mustUpdateRessources) {
  71917. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  71918. }
  71919. else {
  71920. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  71921. }
  71922. }
  71923. else {
  71924. if (errorCallback) {
  71925. errorCallback();
  71926. }
  71927. }
  71928. });
  71929. };
  71930. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  71931. if (this.isSupported && this.db) {
  71932. var targetStore;
  71933. if (url.indexOf(".babylon") !== -1) {
  71934. targetStore = "scenes";
  71935. }
  71936. else {
  71937. targetStore = "textures";
  71938. }
  71939. var file;
  71940. var transaction = this.db.transaction([targetStore]);
  71941. transaction.oncomplete = function (event) {
  71942. if (file) {
  71943. callback(file.data);
  71944. }
  71945. // file was not found in DB
  71946. else {
  71947. notInDBCallback();
  71948. }
  71949. };
  71950. transaction.onabort = function (event) {
  71951. notInDBCallback();
  71952. };
  71953. var getRequest = transaction.objectStore(targetStore).get(url);
  71954. getRequest.onsuccess = function (event) {
  71955. file = (event.target).result;
  71956. };
  71957. getRequest.onerror = function (event) {
  71958. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  71959. notInDBCallback();
  71960. };
  71961. }
  71962. else {
  71963. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71964. callback();
  71965. }
  71966. };
  71967. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  71968. var _this = this;
  71969. if (this.isSupported) {
  71970. var targetStore;
  71971. if (url.indexOf(".babylon") !== -1) {
  71972. targetStore = "scenes";
  71973. }
  71974. else {
  71975. targetStore = "textures";
  71976. }
  71977. // Create XHR
  71978. var xhr = new XMLHttpRequest();
  71979. var fileData;
  71980. xhr.open("GET", url + "?" + Date.now(), true);
  71981. if (useArrayBuffer) {
  71982. xhr.responseType = "arraybuffer";
  71983. }
  71984. if (progressCallback) {
  71985. xhr.onprogress = progressCallback;
  71986. }
  71987. xhr.addEventListener("load", function () {
  71988. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  71989. // Blob as response (XHR2)
  71990. //fileData = xhr.responseText;
  71991. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  71992. if (!_this.hasReachedQuota && _this.db) {
  71993. // Open a transaction to the database
  71994. var transaction = _this.db.transaction([targetStore], "readwrite");
  71995. // the transaction could abort because of a QuotaExceededError error
  71996. transaction.onabort = function (event) {
  71997. try {
  71998. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71999. var error = event.srcElement['error'];
  72000. if (error && error.name === "QuotaExceededError") {
  72001. _this.hasReachedQuota = true;
  72002. }
  72003. }
  72004. catch (ex) { }
  72005. callback(fileData);
  72006. };
  72007. transaction.oncomplete = function (event) {
  72008. callback(fileData);
  72009. };
  72010. var newFile;
  72011. if (targetStore === "scenes") {
  72012. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  72013. }
  72014. else {
  72015. newFile = { textureUrl: url, data: fileData };
  72016. }
  72017. try {
  72018. // Put the scene into the database
  72019. var addRequest = transaction.objectStore(targetStore).put(newFile);
  72020. addRequest.onsuccess = function (event) {
  72021. };
  72022. addRequest.onerror = function (event) {
  72023. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  72024. };
  72025. }
  72026. catch (ex) {
  72027. callback(fileData);
  72028. }
  72029. }
  72030. else {
  72031. callback(fileData);
  72032. }
  72033. }
  72034. else {
  72035. if (xhr.status >= 400 && errorCallback) {
  72036. errorCallback(xhr);
  72037. }
  72038. else {
  72039. callback();
  72040. }
  72041. }
  72042. }, false);
  72043. xhr.addEventListener("error", function (event) {
  72044. BABYLON.Tools.Error("error on XHR request.");
  72045. callback();
  72046. }, false);
  72047. xhr.send();
  72048. }
  72049. else {
  72050. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72051. callback();
  72052. }
  72053. };
  72054. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  72055. Database.IsUASupportingBlobStorage = true;
  72056. /** Gets a boolean indicating if Database storate is enabled */
  72057. Database.IDBStorageEnabled = true;
  72058. Database._ParseURL = function (url) {
  72059. var a = document.createElement('a');
  72060. a.href = url;
  72061. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  72062. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  72063. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  72064. return absLocation;
  72065. };
  72066. Database._ReturnFullUrlLocation = function (url) {
  72067. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  72068. return (Database._ParseURL(window.location.href) + url);
  72069. }
  72070. else {
  72071. return url;
  72072. }
  72073. };
  72074. return Database;
  72075. }());
  72076. BABYLON.Database = Database;
  72077. })(BABYLON || (BABYLON = {}));
  72078. //# sourceMappingURL=babylon.database.js.map
  72079. var BABYLON;
  72080. (function (BABYLON) {
  72081. var FresnelParameters = /** @class */ (function () {
  72082. function FresnelParameters() {
  72083. this._isEnabled = true;
  72084. this.leftColor = BABYLON.Color3.White();
  72085. this.rightColor = BABYLON.Color3.Black();
  72086. this.bias = 0;
  72087. this.power = 1;
  72088. }
  72089. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  72090. get: function () {
  72091. return this._isEnabled;
  72092. },
  72093. set: function (value) {
  72094. if (this._isEnabled === value) {
  72095. return;
  72096. }
  72097. this._isEnabled = value;
  72098. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  72099. },
  72100. enumerable: true,
  72101. configurable: true
  72102. });
  72103. FresnelParameters.prototype.clone = function () {
  72104. var newFresnelParameters = new FresnelParameters();
  72105. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  72106. return newFresnelParameters;
  72107. };
  72108. FresnelParameters.prototype.serialize = function () {
  72109. var serializationObject = {};
  72110. serializationObject.isEnabled = this.isEnabled;
  72111. serializationObject.leftColor = this.leftColor.asArray();
  72112. serializationObject.rightColor = this.rightColor.asArray();
  72113. serializationObject.bias = this.bias;
  72114. serializationObject.power = this.power;
  72115. return serializationObject;
  72116. };
  72117. FresnelParameters.Parse = function (parsedFresnelParameters) {
  72118. var fresnelParameters = new FresnelParameters();
  72119. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  72120. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  72121. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  72122. fresnelParameters.bias = parsedFresnelParameters.bias;
  72123. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  72124. return fresnelParameters;
  72125. };
  72126. return FresnelParameters;
  72127. }());
  72128. BABYLON.FresnelParameters = FresnelParameters;
  72129. })(BABYLON || (BABYLON = {}));
  72130. //# sourceMappingURL=babylon.fresnelParameters.js.map
  72131. var BABYLON;
  72132. (function (BABYLON) {
  72133. var MultiMaterial = /** @class */ (function (_super) {
  72134. __extends(MultiMaterial, _super);
  72135. function MultiMaterial(name, scene) {
  72136. var _this = _super.call(this, name, scene, true) || this;
  72137. scene.multiMaterials.push(_this);
  72138. _this.subMaterials = new Array();
  72139. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  72140. return _this;
  72141. }
  72142. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  72143. get: function () {
  72144. return this._subMaterials;
  72145. },
  72146. set: function (value) {
  72147. this._subMaterials = value;
  72148. this._hookArray(value);
  72149. },
  72150. enumerable: true,
  72151. configurable: true
  72152. });
  72153. MultiMaterial.prototype._hookArray = function (array) {
  72154. var _this = this;
  72155. var oldPush = array.push;
  72156. array.push = function () {
  72157. var items = [];
  72158. for (var _i = 0; _i < arguments.length; _i++) {
  72159. items[_i] = arguments[_i];
  72160. }
  72161. var result = oldPush.apply(array, items);
  72162. _this._markAllSubMeshesAsTexturesDirty();
  72163. return result;
  72164. };
  72165. var oldSplice = array.splice;
  72166. array.splice = function (index, deleteCount) {
  72167. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72168. _this._markAllSubMeshesAsTexturesDirty();
  72169. return deleted;
  72170. };
  72171. };
  72172. // Properties
  72173. MultiMaterial.prototype.getSubMaterial = function (index) {
  72174. if (index < 0 || index >= this.subMaterials.length) {
  72175. return this.getScene().defaultMaterial;
  72176. }
  72177. return this.subMaterials[index];
  72178. };
  72179. MultiMaterial.prototype.getActiveTextures = function () {
  72180. var _a;
  72181. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  72182. if (subMaterial) {
  72183. return subMaterial.getActiveTextures();
  72184. }
  72185. else {
  72186. return [];
  72187. }
  72188. }));
  72189. };
  72190. // Methods
  72191. MultiMaterial.prototype.getClassName = function () {
  72192. return "MultiMaterial";
  72193. };
  72194. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72195. for (var index = 0; index < this.subMaterials.length; index++) {
  72196. var subMaterial = this.subMaterials[index];
  72197. if (subMaterial) {
  72198. if (subMaterial.storeEffectOnSubMeshes) {
  72199. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  72200. return false;
  72201. }
  72202. continue;
  72203. }
  72204. if (!subMaterial.isReady(mesh)) {
  72205. return false;
  72206. }
  72207. }
  72208. }
  72209. return true;
  72210. };
  72211. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  72212. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  72213. for (var index = 0; index < this.subMaterials.length; index++) {
  72214. var subMaterial = null;
  72215. var current = this.subMaterials[index];
  72216. if (cloneChildren && current) {
  72217. subMaterial = current.clone(name + "-" + current.name);
  72218. }
  72219. else {
  72220. subMaterial = this.subMaterials[index];
  72221. }
  72222. newMultiMaterial.subMaterials.push(subMaterial);
  72223. }
  72224. return newMultiMaterial;
  72225. };
  72226. MultiMaterial.prototype.serialize = function () {
  72227. var serializationObject = {};
  72228. serializationObject.name = this.name;
  72229. serializationObject.id = this.id;
  72230. if (BABYLON.Tags) {
  72231. serializationObject.tags = BABYLON.Tags.GetTags(this);
  72232. }
  72233. serializationObject.materials = [];
  72234. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  72235. var subMat = this.subMaterials[matIndex];
  72236. if (subMat) {
  72237. serializationObject.materials.push(subMat.id);
  72238. }
  72239. else {
  72240. serializationObject.materials.push(null);
  72241. }
  72242. }
  72243. return serializationObject;
  72244. };
  72245. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  72246. var scene = this.getScene();
  72247. if (!scene) {
  72248. return;
  72249. }
  72250. var index = scene.multiMaterials.indexOf(this);
  72251. if (index >= 0) {
  72252. scene.multiMaterials.splice(index, 1);
  72253. }
  72254. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  72255. };
  72256. return MultiMaterial;
  72257. }(BABYLON.Material));
  72258. BABYLON.MultiMaterial = MultiMaterial;
  72259. })(BABYLON || (BABYLON = {}));
  72260. //# sourceMappingURL=babylon.multiMaterial.js.map
  72261. var BABYLON;
  72262. (function (BABYLON) {
  72263. var FreeCameraTouchInput = /** @class */ (function () {
  72264. function FreeCameraTouchInput() {
  72265. this._offsetX = null;
  72266. this._offsetY = null;
  72267. this._pointerPressed = new Array();
  72268. this.touchAngularSensibility = 200000.0;
  72269. this.touchMoveSensibility = 250.0;
  72270. }
  72271. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  72272. var _this = this;
  72273. var previousPosition = null;
  72274. if (this._pointerInput === undefined) {
  72275. this._onLostFocus = function (evt) {
  72276. _this._offsetX = null;
  72277. _this._offsetY = null;
  72278. };
  72279. this._pointerInput = function (p, s) {
  72280. var evt = p.event;
  72281. if (evt.pointerType === "mouse") {
  72282. return;
  72283. }
  72284. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72285. if (!noPreventDefault) {
  72286. evt.preventDefault();
  72287. }
  72288. _this._pointerPressed.push(evt.pointerId);
  72289. if (_this._pointerPressed.length !== 1) {
  72290. return;
  72291. }
  72292. previousPosition = {
  72293. x: evt.clientX,
  72294. y: evt.clientY
  72295. };
  72296. }
  72297. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  72298. if (!noPreventDefault) {
  72299. evt.preventDefault();
  72300. }
  72301. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72302. if (index === -1) {
  72303. return;
  72304. }
  72305. _this._pointerPressed.splice(index, 1);
  72306. if (index != 0) {
  72307. return;
  72308. }
  72309. previousPosition = null;
  72310. _this._offsetX = null;
  72311. _this._offsetY = null;
  72312. }
  72313. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  72314. if (!noPreventDefault) {
  72315. evt.preventDefault();
  72316. }
  72317. if (!previousPosition) {
  72318. return;
  72319. }
  72320. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72321. if (index != 0) {
  72322. return;
  72323. }
  72324. _this._offsetX = evt.clientX - previousPosition.x;
  72325. _this._offsetY = -(evt.clientY - previousPosition.y);
  72326. }
  72327. };
  72328. }
  72329. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  72330. if (this._onLostFocus) {
  72331. element.addEventListener("blur", this._onLostFocus);
  72332. }
  72333. };
  72334. FreeCameraTouchInput.prototype.detachControl = function (element) {
  72335. if (this._pointerInput && element) {
  72336. if (this._observer) {
  72337. this.camera.getScene().onPointerObservable.remove(this._observer);
  72338. this._observer = null;
  72339. }
  72340. if (this._onLostFocus) {
  72341. element.removeEventListener("blur", this._onLostFocus);
  72342. this._onLostFocus = null;
  72343. }
  72344. this._pointerPressed = [];
  72345. this._offsetX = null;
  72346. this._offsetY = null;
  72347. }
  72348. };
  72349. FreeCameraTouchInput.prototype.checkInputs = function () {
  72350. if (this._offsetX && this._offsetY) {
  72351. var camera = this.camera;
  72352. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  72353. if (this._pointerPressed.length > 1) {
  72354. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  72355. }
  72356. else {
  72357. var speed = camera._computeLocalCameraSpeed();
  72358. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  72359. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  72360. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  72361. }
  72362. }
  72363. };
  72364. FreeCameraTouchInput.prototype.getClassName = function () {
  72365. return "FreeCameraTouchInput";
  72366. };
  72367. FreeCameraTouchInput.prototype.getSimpleName = function () {
  72368. return "touch";
  72369. };
  72370. __decorate([
  72371. BABYLON.serialize()
  72372. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  72373. __decorate([
  72374. BABYLON.serialize()
  72375. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  72376. return FreeCameraTouchInput;
  72377. }());
  72378. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  72379. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  72380. })(BABYLON || (BABYLON = {}));
  72381. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  72382. var BABYLON;
  72383. (function (BABYLON) {
  72384. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  72385. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  72386. });
  72387. // We're mainly based on the logic defined into the FreeCamera code
  72388. var TouchCamera = /** @class */ (function (_super) {
  72389. __extends(TouchCamera, _super);
  72390. //-- end properties for backward compatibility for inputs
  72391. function TouchCamera(name, position, scene) {
  72392. var _this = _super.call(this, name, position, scene) || this;
  72393. _this.inputs.addTouch();
  72394. _this._setupInputs();
  72395. return _this;
  72396. }
  72397. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  72398. //-- Begin properties for backward compatibility for inputs
  72399. get: function () {
  72400. var touch = this.inputs.attached["touch"];
  72401. if (touch)
  72402. return touch.touchAngularSensibility;
  72403. return 0;
  72404. },
  72405. set: function (value) {
  72406. var touch = this.inputs.attached["touch"];
  72407. if (touch)
  72408. touch.touchAngularSensibility = value;
  72409. },
  72410. enumerable: true,
  72411. configurable: true
  72412. });
  72413. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  72414. get: function () {
  72415. var touch = this.inputs.attached["touch"];
  72416. if (touch)
  72417. return touch.touchMoveSensibility;
  72418. return 0;
  72419. },
  72420. set: function (value) {
  72421. var touch = this.inputs.attached["touch"];
  72422. if (touch)
  72423. touch.touchMoveSensibility = value;
  72424. },
  72425. enumerable: true,
  72426. configurable: true
  72427. });
  72428. TouchCamera.prototype.getClassName = function () {
  72429. return "TouchCamera";
  72430. };
  72431. /** @hidden */
  72432. TouchCamera.prototype._setupInputs = function () {
  72433. var mouse = this.inputs.attached["mouse"];
  72434. if (mouse) {
  72435. mouse.touchEnabled = false;
  72436. }
  72437. };
  72438. return TouchCamera;
  72439. }(BABYLON.FreeCamera));
  72440. BABYLON.TouchCamera = TouchCamera;
  72441. })(BABYLON || (BABYLON = {}));
  72442. //# sourceMappingURL=babylon.touchCamera.js.map
  72443. var BABYLON;
  72444. (function (BABYLON) {
  72445. var ProceduralTexture = /** @class */ (function (_super) {
  72446. __extends(ProceduralTexture, _super);
  72447. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  72448. if (fallbackTexture === void 0) { fallbackTexture = null; }
  72449. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72450. if (isCube === void 0) { isCube = false; }
  72451. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  72452. _this.isCube = isCube;
  72453. _this.isEnabled = true;
  72454. _this._currentRefreshId = -1;
  72455. _this._refreshRate = 1;
  72456. _this._vertexBuffers = {};
  72457. _this._uniforms = new Array();
  72458. _this._samplers = new Array();
  72459. /** @hidden */
  72460. _this._textures = {};
  72461. _this._floats = {};
  72462. _this._ints = {};
  72463. _this._floatsArrays = {};
  72464. _this._colors3 = {};
  72465. _this._colors4 = {};
  72466. _this._vectors2 = {};
  72467. _this._vectors3 = {};
  72468. _this._matrices = {};
  72469. _this._fallbackTextureUsed = false;
  72470. scene = _this.getScene();
  72471. scene.proceduralTextures.push(_this);
  72472. _this._engine = scene.getEngine();
  72473. _this.name = name;
  72474. _this.isRenderTarget = true;
  72475. _this._size = size;
  72476. _this._generateMipMaps = generateMipMaps;
  72477. _this.setFragment(fragment);
  72478. _this._fallbackTexture = fallbackTexture;
  72479. if (isCube) {
  72480. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  72481. _this.setFloat("face", 0);
  72482. }
  72483. else {
  72484. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  72485. }
  72486. // VBO
  72487. var vertices = [];
  72488. vertices.push(1, 1);
  72489. vertices.push(-1, 1);
  72490. vertices.push(-1, -1);
  72491. vertices.push(1, -1);
  72492. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72493. _this._createIndexBuffer();
  72494. return _this;
  72495. }
  72496. ProceduralTexture.prototype._createIndexBuffer = function () {
  72497. var engine = this._engine;
  72498. // Indices
  72499. var indices = [];
  72500. indices.push(0);
  72501. indices.push(1);
  72502. indices.push(2);
  72503. indices.push(0);
  72504. indices.push(2);
  72505. indices.push(3);
  72506. this._indexBuffer = engine.createIndexBuffer(indices);
  72507. };
  72508. /** @hidden */
  72509. ProceduralTexture.prototype._rebuild = function () {
  72510. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72511. if (vb) {
  72512. vb._rebuild();
  72513. }
  72514. this._createIndexBuffer();
  72515. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72516. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72517. }
  72518. };
  72519. ProceduralTexture.prototype.reset = function () {
  72520. if (this._effect === undefined) {
  72521. return;
  72522. }
  72523. var engine = this._engine;
  72524. engine._releaseEffect(this._effect);
  72525. };
  72526. ProceduralTexture.prototype.isReady = function () {
  72527. var _this = this;
  72528. var engine = this._engine;
  72529. var shaders;
  72530. if (!this._fragment) {
  72531. return false;
  72532. }
  72533. if (this._fallbackTextureUsed) {
  72534. return true;
  72535. }
  72536. if (this._fragment.fragmentElement !== undefined) {
  72537. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  72538. }
  72539. else {
  72540. shaders = { vertex: "procedural", fragment: this._fragment };
  72541. }
  72542. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  72543. _this.releaseInternalTexture();
  72544. if (_this._fallbackTexture) {
  72545. _this._texture = _this._fallbackTexture._texture;
  72546. if (_this._texture) {
  72547. _this._texture.incrementReferences();
  72548. }
  72549. }
  72550. _this._fallbackTextureUsed = true;
  72551. });
  72552. return this._effect.isReady();
  72553. };
  72554. ProceduralTexture.prototype.resetRefreshCounter = function () {
  72555. this._currentRefreshId = -1;
  72556. };
  72557. ProceduralTexture.prototype.setFragment = function (fragment) {
  72558. this._fragment = fragment;
  72559. };
  72560. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  72561. get: function () {
  72562. return this._refreshRate;
  72563. },
  72564. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  72565. set: function (value) {
  72566. this._refreshRate = value;
  72567. this.resetRefreshCounter();
  72568. },
  72569. enumerable: true,
  72570. configurable: true
  72571. });
  72572. /** @hidden */
  72573. ProceduralTexture.prototype._shouldRender = function () {
  72574. if (!this.isEnabled || !this.isReady() || !this._texture) {
  72575. return false;
  72576. }
  72577. if (this._fallbackTextureUsed) {
  72578. return false;
  72579. }
  72580. if (this._currentRefreshId === -1) { // At least render once
  72581. this._currentRefreshId = 1;
  72582. return true;
  72583. }
  72584. if (this.refreshRate === this._currentRefreshId) {
  72585. this._currentRefreshId = 1;
  72586. return true;
  72587. }
  72588. this._currentRefreshId++;
  72589. return false;
  72590. };
  72591. ProceduralTexture.prototype.getRenderSize = function () {
  72592. return this._size;
  72593. };
  72594. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  72595. if (this._fallbackTextureUsed) {
  72596. return;
  72597. }
  72598. this.releaseInternalTexture();
  72599. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  72600. // Update properties
  72601. this._size = size;
  72602. this._generateMipMaps = generateMipMaps;
  72603. };
  72604. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  72605. if (this._uniforms.indexOf(uniformName) === -1) {
  72606. this._uniforms.push(uniformName);
  72607. }
  72608. };
  72609. ProceduralTexture.prototype.setTexture = function (name, texture) {
  72610. if (this._samplers.indexOf(name) === -1) {
  72611. this._samplers.push(name);
  72612. }
  72613. this._textures[name] = texture;
  72614. return this;
  72615. };
  72616. ProceduralTexture.prototype.setFloat = function (name, value) {
  72617. this._checkUniform(name);
  72618. this._floats[name] = value;
  72619. return this;
  72620. };
  72621. /**
  72622. * Set the value of an uniform to an integer value
  72623. * @param name defines the name of the uniform
  72624. * @param value defines the value to set
  72625. * @returns the current procedural texture
  72626. */
  72627. ProceduralTexture.prototype.setInt = function (name, value) {
  72628. this._checkUniform(name);
  72629. this._ints[name] = value;
  72630. return this;
  72631. };
  72632. ProceduralTexture.prototype.setFloats = function (name, value) {
  72633. this._checkUniform(name);
  72634. this._floatsArrays[name] = value;
  72635. return this;
  72636. };
  72637. ProceduralTexture.prototype.setColor3 = function (name, value) {
  72638. this._checkUniform(name);
  72639. this._colors3[name] = value;
  72640. return this;
  72641. };
  72642. ProceduralTexture.prototype.setColor4 = function (name, value) {
  72643. this._checkUniform(name);
  72644. this._colors4[name] = value;
  72645. return this;
  72646. };
  72647. ProceduralTexture.prototype.setVector2 = function (name, value) {
  72648. this._checkUniform(name);
  72649. this._vectors2[name] = value;
  72650. return this;
  72651. };
  72652. ProceduralTexture.prototype.setVector3 = function (name, value) {
  72653. this._checkUniform(name);
  72654. this._vectors3[name] = value;
  72655. return this;
  72656. };
  72657. ProceduralTexture.prototype.setMatrix = function (name, value) {
  72658. this._checkUniform(name);
  72659. this._matrices[name] = value;
  72660. return this;
  72661. };
  72662. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  72663. var scene = this.getScene();
  72664. if (!scene) {
  72665. return;
  72666. }
  72667. var engine = this._engine;
  72668. // Render
  72669. engine.enableEffect(this._effect);
  72670. engine.setState(false);
  72671. // Texture
  72672. for (var name in this._textures) {
  72673. this._effect.setTexture(name, this._textures[name]);
  72674. }
  72675. // Float
  72676. for (name in this._ints) {
  72677. this._effect.setInt(name, this._ints[name]);
  72678. }
  72679. // Float
  72680. for (name in this._floats) {
  72681. this._effect.setFloat(name, this._floats[name]);
  72682. }
  72683. // Floats
  72684. for (name in this._floatsArrays) {
  72685. this._effect.setArray(name, this._floatsArrays[name]);
  72686. }
  72687. // Color3
  72688. for (name in this._colors3) {
  72689. this._effect.setColor3(name, this._colors3[name]);
  72690. }
  72691. // Color4
  72692. for (name in this._colors4) {
  72693. var color = this._colors4[name];
  72694. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  72695. }
  72696. // Vector2
  72697. for (name in this._vectors2) {
  72698. this._effect.setVector2(name, this._vectors2[name]);
  72699. }
  72700. // Vector3
  72701. for (name in this._vectors3) {
  72702. this._effect.setVector3(name, this._vectors3[name]);
  72703. }
  72704. // Matrix
  72705. for (name in this._matrices) {
  72706. this._effect.setMatrix(name, this._matrices[name]);
  72707. }
  72708. if (!this._texture) {
  72709. return;
  72710. }
  72711. if (this.isCube) {
  72712. for (var face = 0; face < 6; face++) {
  72713. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  72714. // VBOs
  72715. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72716. this._effect.setFloat("face", face);
  72717. // Clear
  72718. engine.clear(scene.clearColor, true, true, true);
  72719. // Draw order
  72720. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72721. // Mipmaps
  72722. if (face === 5) {
  72723. engine.generateMipMapsForCubemap(this._texture);
  72724. }
  72725. }
  72726. }
  72727. else {
  72728. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  72729. // VBOs
  72730. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72731. // Clear
  72732. engine.clear(scene.clearColor, true, true, true);
  72733. // Draw order
  72734. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72735. }
  72736. // Unbind
  72737. engine.unBindFramebuffer(this._texture, this.isCube);
  72738. if (this.onGenerated) {
  72739. this.onGenerated();
  72740. }
  72741. };
  72742. ProceduralTexture.prototype.clone = function () {
  72743. var textureSize = this.getSize();
  72744. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  72745. // Base texture
  72746. newTexture.hasAlpha = this.hasAlpha;
  72747. newTexture.level = this.level;
  72748. // RenderTarget Texture
  72749. newTexture.coordinatesMode = this.coordinatesMode;
  72750. return newTexture;
  72751. };
  72752. ProceduralTexture.prototype.dispose = function () {
  72753. var scene = this.getScene();
  72754. if (!scene) {
  72755. return;
  72756. }
  72757. var index = scene.proceduralTextures.indexOf(this);
  72758. if (index >= 0) {
  72759. scene.proceduralTextures.splice(index, 1);
  72760. }
  72761. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72762. if (vertexBuffer) {
  72763. vertexBuffer.dispose();
  72764. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72765. }
  72766. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  72767. this._indexBuffer = null;
  72768. }
  72769. _super.prototype.dispose.call(this);
  72770. };
  72771. __decorate([
  72772. BABYLON.serialize()
  72773. ], ProceduralTexture.prototype, "_size", void 0);
  72774. __decorate([
  72775. BABYLON.serialize()
  72776. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  72777. __decorate([
  72778. BABYLON.serialize()
  72779. ], ProceduralTexture.prototype, "isEnabled", void 0);
  72780. __decorate([
  72781. BABYLON.serialize()
  72782. ], ProceduralTexture.prototype, "refreshRate", null);
  72783. return ProceduralTexture;
  72784. }(BABYLON.Texture));
  72785. BABYLON.ProceduralTexture = ProceduralTexture;
  72786. })(BABYLON || (BABYLON = {}));
  72787. //# sourceMappingURL=babylon.proceduralTexture.js.map
  72788. var BABYLON;
  72789. (function (BABYLON) {
  72790. var CustomProceduralTexture = /** @class */ (function (_super) {
  72791. __extends(CustomProceduralTexture, _super);
  72792. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  72793. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  72794. _this._animate = true;
  72795. _this._time = 0;
  72796. _this._texturePath = texturePath;
  72797. //Try to load json
  72798. _this.loadJson(texturePath);
  72799. _this.refreshRate = 1;
  72800. return _this;
  72801. }
  72802. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  72803. var _this = this;
  72804. var noConfigFile = function () {
  72805. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  72806. try {
  72807. _this.setFragment(_this._texturePath);
  72808. }
  72809. catch (ex) {
  72810. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  72811. }
  72812. };
  72813. var configFileUrl = jsonUrl + "/config.json";
  72814. var xhr = new XMLHttpRequest();
  72815. xhr.open("GET", configFileUrl, true);
  72816. xhr.addEventListener("load", function () {
  72817. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72818. try {
  72819. _this._config = JSON.parse(xhr.response);
  72820. _this.updateShaderUniforms();
  72821. _this.updateTextures();
  72822. _this.setFragment(_this._texturePath + "/custom");
  72823. _this._animate = _this._config.animate;
  72824. _this.refreshRate = _this._config.refreshrate;
  72825. }
  72826. catch (ex) {
  72827. noConfigFile();
  72828. }
  72829. }
  72830. else {
  72831. noConfigFile();
  72832. }
  72833. }, false);
  72834. xhr.addEventListener("error", function () {
  72835. noConfigFile();
  72836. }, false);
  72837. try {
  72838. xhr.send();
  72839. }
  72840. catch (ex) {
  72841. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  72842. }
  72843. };
  72844. CustomProceduralTexture.prototype.isReady = function () {
  72845. if (!_super.prototype.isReady.call(this)) {
  72846. return false;
  72847. }
  72848. for (var name in this._textures) {
  72849. var texture = this._textures[name];
  72850. if (!texture.isReady()) {
  72851. return false;
  72852. }
  72853. }
  72854. return true;
  72855. };
  72856. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  72857. var scene = this.getScene();
  72858. if (this._animate && scene) {
  72859. this._time += scene.getAnimationRatio() * 0.03;
  72860. this.updateShaderUniforms();
  72861. }
  72862. _super.prototype.render.call(this, useCameraPostProcess);
  72863. };
  72864. CustomProceduralTexture.prototype.updateTextures = function () {
  72865. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  72866. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  72867. }
  72868. };
  72869. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  72870. if (this._config) {
  72871. for (var j = 0; j < this._config.uniforms.length; j++) {
  72872. var uniform = this._config.uniforms[j];
  72873. switch (uniform.type) {
  72874. case "float":
  72875. this.setFloat(uniform.name, uniform.value);
  72876. break;
  72877. case "color3":
  72878. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  72879. break;
  72880. case "color4":
  72881. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  72882. break;
  72883. case "vector2":
  72884. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  72885. break;
  72886. case "vector3":
  72887. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  72888. break;
  72889. }
  72890. }
  72891. }
  72892. this.setFloat("time", this._time);
  72893. };
  72894. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  72895. get: function () {
  72896. return this._animate;
  72897. },
  72898. set: function (value) {
  72899. this._animate = value;
  72900. },
  72901. enumerable: true,
  72902. configurable: true
  72903. });
  72904. return CustomProceduralTexture;
  72905. }(BABYLON.ProceduralTexture));
  72906. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  72907. })(BABYLON || (BABYLON = {}));
  72908. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  72909. var BABYLON;
  72910. (function (BABYLON) {
  72911. var FreeCameraGamepadInput = /** @class */ (function () {
  72912. function FreeCameraGamepadInput() {
  72913. this.gamepadAngularSensibility = 200;
  72914. this.gamepadMoveSensibility = 40;
  72915. // private members
  72916. this._cameraTransform = BABYLON.Matrix.Identity();
  72917. this._deltaTransform = BABYLON.Vector3.Zero();
  72918. this._vector3 = BABYLON.Vector3.Zero();
  72919. this._vector2 = BABYLON.Vector2.Zero();
  72920. }
  72921. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72922. var _this = this;
  72923. var manager = this.camera.getScene().gamepadManager;
  72924. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72925. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72926. // prioritize XBOX gamepads.
  72927. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72928. _this.gamepad = gamepad;
  72929. }
  72930. }
  72931. });
  72932. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72933. if (_this.gamepad === gamepad) {
  72934. _this.gamepad = null;
  72935. }
  72936. });
  72937. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72938. };
  72939. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  72940. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72941. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72942. this.gamepad = null;
  72943. };
  72944. FreeCameraGamepadInput.prototype.checkInputs = function () {
  72945. if (this.gamepad && this.gamepad.leftStick) {
  72946. var camera = this.camera;
  72947. var LSValues = this.gamepad.leftStick;
  72948. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  72949. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72950. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  72951. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  72952. var RSValues = this.gamepad.rightStick;
  72953. if (RSValues) {
  72954. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  72955. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  72956. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  72957. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  72958. }
  72959. else {
  72960. RSValues = { x: 0, y: 0 };
  72961. }
  72962. if (!camera.rotationQuaternion) {
  72963. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  72964. }
  72965. else {
  72966. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  72967. }
  72968. var speed = camera._computeLocalCameraSpeed() * 50.0;
  72969. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  72970. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  72971. camera.cameraDirection.addInPlace(this._deltaTransform);
  72972. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  72973. camera.cameraRotation.addInPlace(this._vector2);
  72974. }
  72975. };
  72976. FreeCameraGamepadInput.prototype.getClassName = function () {
  72977. return "FreeCameraGamepadInput";
  72978. };
  72979. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  72980. return "gamepad";
  72981. };
  72982. __decorate([
  72983. BABYLON.serialize()
  72984. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  72985. __decorate([
  72986. BABYLON.serialize()
  72987. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72988. return FreeCameraGamepadInput;
  72989. }());
  72990. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  72991. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  72992. })(BABYLON || (BABYLON = {}));
  72993. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  72994. var BABYLON;
  72995. (function (BABYLON) {
  72996. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  72997. function ArcRotateCameraGamepadInput() {
  72998. this.gamepadRotationSensibility = 80;
  72999. this.gamepadMoveSensibility = 40;
  73000. }
  73001. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73002. var _this = this;
  73003. var manager = this.camera.getScene().gamepadManager;
  73004. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73005. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73006. // prioritize XBOX gamepads.
  73007. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73008. _this.gamepad = gamepad;
  73009. }
  73010. }
  73011. });
  73012. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73013. if (_this.gamepad === gamepad) {
  73014. _this.gamepad = null;
  73015. }
  73016. });
  73017. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73018. };
  73019. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  73020. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73021. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73022. this.gamepad = null;
  73023. };
  73024. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  73025. if (this.gamepad) {
  73026. var camera = this.camera;
  73027. var RSValues = this.gamepad.rightStick;
  73028. if (RSValues) {
  73029. if (RSValues.x != 0) {
  73030. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  73031. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  73032. camera.inertialAlphaOffset += normalizedRX;
  73033. }
  73034. }
  73035. if (RSValues.y != 0) {
  73036. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  73037. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  73038. camera.inertialBetaOffset += normalizedRY;
  73039. }
  73040. }
  73041. }
  73042. var LSValues = this.gamepad.leftStick;
  73043. if (LSValues && LSValues.y != 0) {
  73044. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73045. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  73046. this.camera.inertialRadiusOffset -= normalizedLY;
  73047. }
  73048. }
  73049. }
  73050. };
  73051. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  73052. return "ArcRotateCameraGamepadInput";
  73053. };
  73054. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  73055. return "gamepad";
  73056. };
  73057. __decorate([
  73058. BABYLON.serialize()
  73059. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  73060. __decorate([
  73061. BABYLON.serialize()
  73062. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73063. return ArcRotateCameraGamepadInput;
  73064. }());
  73065. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  73066. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  73067. })(BABYLON || (BABYLON = {}));
  73068. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  73069. var BABYLON;
  73070. (function (BABYLON) {
  73071. var GamepadManager = /** @class */ (function () {
  73072. function GamepadManager(_scene) {
  73073. var _this = this;
  73074. this._scene = _scene;
  73075. this._babylonGamepads = [];
  73076. this._oneGamepadConnected = false;
  73077. /** @hidden */
  73078. this._isMonitoring = false;
  73079. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  73080. if (!BABYLON.Tools.IsWindowObjectExist()) {
  73081. this._gamepadEventSupported = false;
  73082. }
  73083. else {
  73084. this._gamepadEventSupported = 'GamepadEvent' in window;
  73085. this._gamepadSupport = (navigator.getGamepads ||
  73086. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  73087. }
  73088. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  73089. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  73090. for (var i in _this._babylonGamepads) {
  73091. var gamepad = _this._babylonGamepads[i];
  73092. if (gamepad && gamepad._isConnected) {
  73093. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  73094. }
  73095. }
  73096. });
  73097. this._onGamepadConnectedEvent = function (evt) {
  73098. var gamepad = evt.gamepad;
  73099. if (gamepad.index in _this._babylonGamepads) {
  73100. if (_this._babylonGamepads[gamepad.index].isConnected) {
  73101. return;
  73102. }
  73103. }
  73104. var newGamepad;
  73105. if (_this._babylonGamepads[gamepad.index]) {
  73106. newGamepad = _this._babylonGamepads[gamepad.index];
  73107. newGamepad.browserGamepad = gamepad;
  73108. newGamepad._isConnected = true;
  73109. }
  73110. else {
  73111. newGamepad = _this._addNewGamepad(gamepad);
  73112. }
  73113. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73114. _this._startMonitoringGamepads();
  73115. };
  73116. this._onGamepadDisconnectedEvent = function (evt) {
  73117. var gamepad = evt.gamepad;
  73118. // Remove the gamepad from the list of gamepads to monitor.
  73119. for (var i in _this._babylonGamepads) {
  73120. if (_this._babylonGamepads[i].index === gamepad.index) {
  73121. var disconnectedGamepad = _this._babylonGamepads[i];
  73122. disconnectedGamepad._isConnected = false;
  73123. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  73124. break;
  73125. }
  73126. }
  73127. };
  73128. if (this._gamepadSupport) {
  73129. //first add already-connected gamepads
  73130. this._updateGamepadObjects();
  73131. if (this._babylonGamepads.length) {
  73132. this._startMonitoringGamepads();
  73133. }
  73134. // Checking if the gamepad connected event is supported (like in Firefox)
  73135. if (this._gamepadEventSupported) {
  73136. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  73137. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  73138. }
  73139. else {
  73140. this._startMonitoringGamepads();
  73141. }
  73142. }
  73143. }
  73144. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  73145. get: function () {
  73146. return this._babylonGamepads;
  73147. },
  73148. enumerable: true,
  73149. configurable: true
  73150. });
  73151. GamepadManager.prototype.getGamepadByType = function (type) {
  73152. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  73153. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  73154. var gamepad = _a[_i];
  73155. if (gamepad && gamepad.type === type) {
  73156. return gamepad;
  73157. }
  73158. }
  73159. return null;
  73160. };
  73161. GamepadManager.prototype.dispose = function () {
  73162. if (this._gamepadEventSupported) {
  73163. if (this._onGamepadConnectedEvent) {
  73164. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  73165. }
  73166. if (this._onGamepadDisconnectedEvent) {
  73167. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  73168. }
  73169. this._onGamepadConnectedEvent = null;
  73170. this._onGamepadDisconnectedEvent = null;
  73171. }
  73172. this._babylonGamepads.forEach(function (gamepad) {
  73173. gamepad.dispose();
  73174. });
  73175. this.onGamepadConnectedObservable.clear();
  73176. this.onGamepadDisconnectedObservable.clear();
  73177. this._oneGamepadConnected = false;
  73178. this._stopMonitoringGamepads();
  73179. this._babylonGamepads = [];
  73180. };
  73181. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  73182. if (!this._oneGamepadConnected) {
  73183. this._oneGamepadConnected = true;
  73184. }
  73185. var newGamepad;
  73186. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  73187. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  73188. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  73189. }
  73190. // if pose is supported, use the (WebVR) pose enabled controller
  73191. else if (gamepad.pose) {
  73192. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  73193. }
  73194. else {
  73195. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  73196. }
  73197. this._babylonGamepads[newGamepad.index] = newGamepad;
  73198. return newGamepad;
  73199. };
  73200. GamepadManager.prototype._startMonitoringGamepads = function () {
  73201. if (!this._isMonitoring) {
  73202. this._isMonitoring = true;
  73203. //back-comp
  73204. if (!this._scene) {
  73205. this._checkGamepadsStatus();
  73206. }
  73207. }
  73208. };
  73209. GamepadManager.prototype._stopMonitoringGamepads = function () {
  73210. this._isMonitoring = false;
  73211. };
  73212. /** @hidden */
  73213. GamepadManager.prototype._checkGamepadsStatus = function () {
  73214. var _this = this;
  73215. // Hack to be compatible Chrome
  73216. this._updateGamepadObjects();
  73217. for (var i in this._babylonGamepads) {
  73218. var gamepad = this._babylonGamepads[i];
  73219. if (!gamepad || !gamepad.isConnected) {
  73220. continue;
  73221. }
  73222. gamepad.update();
  73223. }
  73224. if (this._isMonitoring && !this._scene) {
  73225. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  73226. }
  73227. };
  73228. // This function is called only on Chrome, which does not properly support
  73229. // connection/disconnection events and forces you to recopy again the gamepad object
  73230. GamepadManager.prototype._updateGamepadObjects = function () {
  73231. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  73232. for (var i = 0; i < gamepads.length; i++) {
  73233. var gamepad = gamepads[i];
  73234. if (gamepad) {
  73235. if (!this._babylonGamepads[gamepad.index]) {
  73236. var newGamepad = this._addNewGamepad(gamepad);
  73237. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73238. }
  73239. else {
  73240. // Forced to copy again this object for Chrome for unknown reason
  73241. this._babylonGamepads[i].browserGamepad = gamepad;
  73242. if (!this._babylonGamepads[i].isConnected) {
  73243. this._babylonGamepads[i]._isConnected = true;
  73244. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  73245. }
  73246. }
  73247. }
  73248. }
  73249. };
  73250. return GamepadManager;
  73251. }());
  73252. BABYLON.GamepadManager = GamepadManager;
  73253. })(BABYLON || (BABYLON = {}));
  73254. //# sourceMappingURL=babylon.gamepadManager.js.map
  73255. var BABYLON;
  73256. (function (BABYLON) {
  73257. var StickValues = /** @class */ (function () {
  73258. function StickValues(x, y) {
  73259. this.x = x;
  73260. this.y = y;
  73261. }
  73262. return StickValues;
  73263. }());
  73264. BABYLON.StickValues = StickValues;
  73265. var Gamepad = /** @class */ (function () {
  73266. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  73267. if (leftStickX === void 0) { leftStickX = 0; }
  73268. if (leftStickY === void 0) { leftStickY = 1; }
  73269. if (rightStickX === void 0) { rightStickX = 2; }
  73270. if (rightStickY === void 0) { rightStickY = 3; }
  73271. this.id = id;
  73272. this.index = index;
  73273. this.browserGamepad = browserGamepad;
  73274. /** @hidden */
  73275. this._isConnected = true;
  73276. this._invertLeftStickY = false;
  73277. this.type = Gamepad.GAMEPAD;
  73278. this._leftStickAxisX = leftStickX;
  73279. this._leftStickAxisY = leftStickY;
  73280. this._rightStickAxisX = rightStickX;
  73281. this._rightStickAxisY = rightStickY;
  73282. if (this.browserGamepad.axes.length >= 2) {
  73283. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73284. }
  73285. if (this.browserGamepad.axes.length >= 4) {
  73286. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73287. }
  73288. }
  73289. Object.defineProperty(Gamepad.prototype, "isConnected", {
  73290. get: function () {
  73291. return this._isConnected;
  73292. },
  73293. enumerable: true,
  73294. configurable: true
  73295. });
  73296. Gamepad.prototype.onleftstickchanged = function (callback) {
  73297. this._onleftstickchanged = callback;
  73298. };
  73299. Gamepad.prototype.onrightstickchanged = function (callback) {
  73300. this._onrightstickchanged = callback;
  73301. };
  73302. Object.defineProperty(Gamepad.prototype, "leftStick", {
  73303. get: function () {
  73304. return this._leftStick;
  73305. },
  73306. set: function (newValues) {
  73307. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  73308. this._onleftstickchanged(newValues);
  73309. }
  73310. this._leftStick = newValues;
  73311. },
  73312. enumerable: true,
  73313. configurable: true
  73314. });
  73315. Object.defineProperty(Gamepad.prototype, "rightStick", {
  73316. get: function () {
  73317. return this._rightStick;
  73318. },
  73319. set: function (newValues) {
  73320. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  73321. this._onrightstickchanged(newValues);
  73322. }
  73323. this._rightStick = newValues;
  73324. },
  73325. enumerable: true,
  73326. configurable: true
  73327. });
  73328. Gamepad.prototype.update = function () {
  73329. if (this._leftStick) {
  73330. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73331. if (this._invertLeftStickY) {
  73332. this.leftStick.y *= -1;
  73333. }
  73334. }
  73335. if (this._rightStick) {
  73336. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73337. }
  73338. };
  73339. Gamepad.prototype.dispose = function () {
  73340. };
  73341. Gamepad.GAMEPAD = 0;
  73342. Gamepad.GENERIC = 1;
  73343. Gamepad.XBOX = 2;
  73344. Gamepad.POSE_ENABLED = 3;
  73345. return Gamepad;
  73346. }());
  73347. BABYLON.Gamepad = Gamepad;
  73348. var GenericPad = /** @class */ (function (_super) {
  73349. __extends(GenericPad, _super);
  73350. function GenericPad(id, index, browserGamepad) {
  73351. var _this = _super.call(this, id, index, browserGamepad) || this;
  73352. _this.onButtonDownObservable = new BABYLON.Observable();
  73353. _this.onButtonUpObservable = new BABYLON.Observable();
  73354. _this.type = Gamepad.GENERIC;
  73355. _this._buttons = new Array(browserGamepad.buttons.length);
  73356. return _this;
  73357. }
  73358. GenericPad.prototype.onbuttondown = function (callback) {
  73359. this._onbuttondown = callback;
  73360. };
  73361. GenericPad.prototype.onbuttonup = function (callback) {
  73362. this._onbuttonup = callback;
  73363. };
  73364. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  73365. if (newValue !== currentValue) {
  73366. if (newValue === 1) {
  73367. if (this._onbuttondown) {
  73368. this._onbuttondown(buttonIndex);
  73369. }
  73370. this.onButtonDownObservable.notifyObservers(buttonIndex);
  73371. }
  73372. if (newValue === 0) {
  73373. if (this._onbuttonup) {
  73374. this._onbuttonup(buttonIndex);
  73375. }
  73376. this.onButtonUpObservable.notifyObservers(buttonIndex);
  73377. }
  73378. }
  73379. return newValue;
  73380. };
  73381. GenericPad.prototype.update = function () {
  73382. _super.prototype.update.call(this);
  73383. for (var index = 0; index < this._buttons.length; index++) {
  73384. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  73385. }
  73386. };
  73387. GenericPad.prototype.dispose = function () {
  73388. _super.prototype.dispose.call(this);
  73389. this.onButtonDownObservable.clear();
  73390. this.onButtonUpObservable.clear();
  73391. };
  73392. return GenericPad;
  73393. }(Gamepad));
  73394. BABYLON.GenericPad = GenericPad;
  73395. })(BABYLON || (BABYLON = {}));
  73396. //# sourceMappingURL=babylon.gamepad.js.map
  73397. var BABYLON;
  73398. (function (BABYLON) {
  73399. /**
  73400. * Defines supported buttons for XBox360 compatible gamepads
  73401. */
  73402. var Xbox360Button;
  73403. (function (Xbox360Button) {
  73404. /** A */
  73405. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  73406. /** B */
  73407. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  73408. /** X */
  73409. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  73410. /** Y */
  73411. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  73412. /** Start */
  73413. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  73414. /** Back */
  73415. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  73416. /** Left button */
  73417. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  73418. /** Right button */
  73419. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  73420. /** Left stick */
  73421. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  73422. /** Right stick */
  73423. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  73424. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  73425. /** Defines values for XBox360 DPad */
  73426. var Xbox360Dpad;
  73427. (function (Xbox360Dpad) {
  73428. /** Up */
  73429. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  73430. /** Down */
  73431. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  73432. /** Left */
  73433. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  73434. /** Right */
  73435. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  73436. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  73437. /**
  73438. * Defines a XBox360 gamepad
  73439. */
  73440. var Xbox360Pad = /** @class */ (function (_super) {
  73441. __extends(Xbox360Pad, _super);
  73442. /**
  73443. * Creates a new XBox360 gamepad object
  73444. * @param id defines the id of this gamepad
  73445. * @param index defines its index
  73446. * @param gamepad defines the internal HTML gamepad object
  73447. * @param xboxOne defines if it is a XBox One gamepad
  73448. */
  73449. function Xbox360Pad(id, index, gamepad, xboxOne) {
  73450. if (xboxOne === void 0) { xboxOne = false; }
  73451. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  73452. _this._leftTrigger = 0;
  73453. _this._rightTrigger = 0;
  73454. /** Observable raised when a button is pressed */
  73455. _this.onButtonDownObservable = new BABYLON.Observable();
  73456. /** Observable raised when a button is released */
  73457. _this.onButtonUpObservable = new BABYLON.Observable();
  73458. /** Observable raised when a pad is pressed */
  73459. _this.onPadDownObservable = new BABYLON.Observable();
  73460. /** Observable raised when a pad is released */
  73461. _this.onPadUpObservable = new BABYLON.Observable();
  73462. _this._buttonA = 0;
  73463. _this._buttonB = 0;
  73464. _this._buttonX = 0;
  73465. _this._buttonY = 0;
  73466. _this._buttonBack = 0;
  73467. _this._buttonStart = 0;
  73468. _this._buttonLB = 0;
  73469. _this._buttonRB = 0;
  73470. _this._buttonLeftStick = 0;
  73471. _this._buttonRightStick = 0;
  73472. _this._dPadUp = 0;
  73473. _this._dPadDown = 0;
  73474. _this._dPadLeft = 0;
  73475. _this._dPadRight = 0;
  73476. _this._isXboxOnePad = false;
  73477. _this.type = BABYLON.Gamepad.XBOX;
  73478. _this._isXboxOnePad = xboxOne;
  73479. return _this;
  73480. }
  73481. /**
  73482. * Defines the callback to call when left trigger is pressed
  73483. * @param callback defines the callback to use
  73484. */
  73485. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  73486. this._onlefttriggerchanged = callback;
  73487. };
  73488. /**
  73489. * Defines the callback to call when right trigger is pressed
  73490. * @param callback defines the callback to use
  73491. */
  73492. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  73493. this._onrighttriggerchanged = callback;
  73494. };
  73495. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  73496. /**
  73497. * Gets or sets left trigger value
  73498. */
  73499. get: function () {
  73500. return this._leftTrigger;
  73501. },
  73502. set: function (newValue) {
  73503. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  73504. this._onlefttriggerchanged(newValue);
  73505. }
  73506. this._leftTrigger = newValue;
  73507. },
  73508. enumerable: true,
  73509. configurable: true
  73510. });
  73511. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  73512. /**
  73513. * Gets or sets right trigger value
  73514. */
  73515. get: function () {
  73516. return this._rightTrigger;
  73517. },
  73518. set: function (newValue) {
  73519. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  73520. this._onrighttriggerchanged(newValue);
  73521. }
  73522. this._rightTrigger = newValue;
  73523. },
  73524. enumerable: true,
  73525. configurable: true
  73526. });
  73527. /**
  73528. * Defines the callback to call when a button is pressed
  73529. * @param callback defines the callback to use
  73530. */
  73531. Xbox360Pad.prototype.onbuttondown = function (callback) {
  73532. this._onbuttondown = callback;
  73533. };
  73534. /**
  73535. * Defines the callback to call when a button is released
  73536. * @param callback defines the callback to use
  73537. */
  73538. Xbox360Pad.prototype.onbuttonup = function (callback) {
  73539. this._onbuttonup = callback;
  73540. };
  73541. /**
  73542. * Defines the callback to call when a pad is pressed
  73543. * @param callback defines the callback to use
  73544. */
  73545. Xbox360Pad.prototype.ondpaddown = function (callback) {
  73546. this._ondpaddown = callback;
  73547. };
  73548. /**
  73549. * Defines the callback to call when a pad is released
  73550. * @param callback defines the callback to use
  73551. */
  73552. Xbox360Pad.prototype.ondpadup = function (callback) {
  73553. this._ondpadup = callback;
  73554. };
  73555. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  73556. if (newValue !== currentValue) {
  73557. if (newValue === 1) {
  73558. if (this._onbuttondown) {
  73559. this._onbuttondown(buttonType);
  73560. }
  73561. this.onButtonDownObservable.notifyObservers(buttonType);
  73562. }
  73563. if (newValue === 0) {
  73564. if (this._onbuttonup) {
  73565. this._onbuttonup(buttonType);
  73566. }
  73567. this.onButtonUpObservable.notifyObservers(buttonType);
  73568. }
  73569. }
  73570. return newValue;
  73571. };
  73572. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  73573. if (newValue !== currentValue) {
  73574. if (newValue === 1) {
  73575. if (this._ondpaddown) {
  73576. this._ondpaddown(buttonType);
  73577. }
  73578. this.onPadDownObservable.notifyObservers(buttonType);
  73579. }
  73580. if (newValue === 0) {
  73581. if (this._ondpadup) {
  73582. this._ondpadup(buttonType);
  73583. }
  73584. this.onPadUpObservable.notifyObservers(buttonType);
  73585. }
  73586. }
  73587. return newValue;
  73588. };
  73589. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  73590. /** Gets or sets value of A button */
  73591. get: function () {
  73592. return this._buttonA;
  73593. },
  73594. set: function (value) {
  73595. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  73596. },
  73597. enumerable: true,
  73598. configurable: true
  73599. });
  73600. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  73601. /** Gets or sets value of B button */
  73602. get: function () {
  73603. return this._buttonB;
  73604. },
  73605. set: function (value) {
  73606. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  73607. },
  73608. enumerable: true,
  73609. configurable: true
  73610. });
  73611. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  73612. /** Gets or sets value of X button */
  73613. get: function () {
  73614. return this._buttonX;
  73615. },
  73616. set: function (value) {
  73617. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  73618. },
  73619. enumerable: true,
  73620. configurable: true
  73621. });
  73622. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  73623. /** Gets or sets value of Y button */
  73624. get: function () {
  73625. return this._buttonY;
  73626. },
  73627. set: function (value) {
  73628. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  73629. },
  73630. enumerable: true,
  73631. configurable: true
  73632. });
  73633. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  73634. /** Gets or sets value of Start button */
  73635. get: function () {
  73636. return this._buttonStart;
  73637. },
  73638. set: function (value) {
  73639. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  73640. },
  73641. enumerable: true,
  73642. configurable: true
  73643. });
  73644. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  73645. /** Gets or sets value of Back button */
  73646. get: function () {
  73647. return this._buttonBack;
  73648. },
  73649. set: function (value) {
  73650. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  73651. },
  73652. enumerable: true,
  73653. configurable: true
  73654. });
  73655. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  73656. /** Gets or sets value of Left button */
  73657. get: function () {
  73658. return this._buttonLB;
  73659. },
  73660. set: function (value) {
  73661. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  73662. },
  73663. enumerable: true,
  73664. configurable: true
  73665. });
  73666. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  73667. /** Gets or sets value of Right button */
  73668. get: function () {
  73669. return this._buttonRB;
  73670. },
  73671. set: function (value) {
  73672. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  73673. },
  73674. enumerable: true,
  73675. configurable: true
  73676. });
  73677. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  73678. /** Gets or sets value of left stick */
  73679. get: function () {
  73680. return this._buttonLeftStick;
  73681. },
  73682. set: function (value) {
  73683. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  73684. },
  73685. enumerable: true,
  73686. configurable: true
  73687. });
  73688. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  73689. /** Gets or sets value of right stick */
  73690. get: function () {
  73691. return this._buttonRightStick;
  73692. },
  73693. set: function (value) {
  73694. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  73695. },
  73696. enumerable: true,
  73697. configurable: true
  73698. });
  73699. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  73700. /** Gets or sets value of DPad up */
  73701. get: function () {
  73702. return this._dPadUp;
  73703. },
  73704. set: function (value) {
  73705. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  73706. },
  73707. enumerable: true,
  73708. configurable: true
  73709. });
  73710. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  73711. /** Gets or sets value of DPad down */
  73712. get: function () {
  73713. return this._dPadDown;
  73714. },
  73715. set: function (value) {
  73716. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  73717. },
  73718. enumerable: true,
  73719. configurable: true
  73720. });
  73721. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  73722. /** Gets or sets value of DPad left */
  73723. get: function () {
  73724. return this._dPadLeft;
  73725. },
  73726. set: function (value) {
  73727. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  73728. },
  73729. enumerable: true,
  73730. configurable: true
  73731. });
  73732. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  73733. /** Gets or sets value of DPad right */
  73734. get: function () {
  73735. return this._dPadRight;
  73736. },
  73737. set: function (value) {
  73738. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  73739. },
  73740. enumerable: true,
  73741. configurable: true
  73742. });
  73743. /**
  73744. * Force the gamepad to synchronize with device values
  73745. */
  73746. Xbox360Pad.prototype.update = function () {
  73747. _super.prototype.update.call(this);
  73748. if (this._isXboxOnePad) {
  73749. this.buttonA = this.browserGamepad.buttons[0].value;
  73750. this.buttonB = this.browserGamepad.buttons[1].value;
  73751. this.buttonX = this.browserGamepad.buttons[2].value;
  73752. this.buttonY = this.browserGamepad.buttons[3].value;
  73753. this.buttonLB = this.browserGamepad.buttons[4].value;
  73754. this.buttonRB = this.browserGamepad.buttons[5].value;
  73755. this.leftTrigger = this.browserGamepad.axes[2];
  73756. this.rightTrigger = this.browserGamepad.axes[5];
  73757. this.buttonBack = this.browserGamepad.buttons[9].value;
  73758. this.buttonStart = this.browserGamepad.buttons[8].value;
  73759. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  73760. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  73761. this.dPadUp = this.browserGamepad.buttons[11].value;
  73762. this.dPadDown = this.browserGamepad.buttons[12].value;
  73763. this.dPadLeft = this.browserGamepad.buttons[13].value;
  73764. this.dPadRight = this.browserGamepad.buttons[14].value;
  73765. }
  73766. else {
  73767. this.buttonA = this.browserGamepad.buttons[0].value;
  73768. this.buttonB = this.browserGamepad.buttons[1].value;
  73769. this.buttonX = this.browserGamepad.buttons[2].value;
  73770. this.buttonY = this.browserGamepad.buttons[3].value;
  73771. this.buttonLB = this.browserGamepad.buttons[4].value;
  73772. this.buttonRB = this.browserGamepad.buttons[5].value;
  73773. this.leftTrigger = this.browserGamepad.buttons[6].value;
  73774. this.rightTrigger = this.browserGamepad.buttons[7].value;
  73775. this.buttonBack = this.browserGamepad.buttons[8].value;
  73776. this.buttonStart = this.browserGamepad.buttons[9].value;
  73777. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  73778. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  73779. this.dPadUp = this.browserGamepad.buttons[12].value;
  73780. this.dPadDown = this.browserGamepad.buttons[13].value;
  73781. this.dPadLeft = this.browserGamepad.buttons[14].value;
  73782. this.dPadRight = this.browserGamepad.buttons[15].value;
  73783. }
  73784. };
  73785. Xbox360Pad.prototype.dispose = function () {
  73786. _super.prototype.dispose.call(this);
  73787. this.onButtonDownObservable.clear();
  73788. this.onButtonUpObservable.clear();
  73789. this.onPadDownObservable.clear();
  73790. this.onPadUpObservable.clear();
  73791. };
  73792. return Xbox360Pad;
  73793. }(BABYLON.Gamepad));
  73794. BABYLON.Xbox360Pad = Xbox360Pad;
  73795. })(BABYLON || (BABYLON = {}));
  73796. //# sourceMappingURL=babylon.xboxGamepad.js.map
  73797. var BABYLON;
  73798. (function (BABYLON) {
  73799. /**
  73800. * Defines the types of pose enabled controllers that are supported
  73801. */
  73802. var PoseEnabledControllerType;
  73803. (function (PoseEnabledControllerType) {
  73804. /**
  73805. * HTC Vive
  73806. */
  73807. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  73808. /**
  73809. * Oculus Rift
  73810. */
  73811. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  73812. /**
  73813. * Windows mixed reality
  73814. */
  73815. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  73816. /**
  73817. * Samsung gear VR
  73818. */
  73819. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  73820. /**
  73821. * Google Daydream
  73822. */
  73823. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  73824. /**
  73825. * Generic
  73826. */
  73827. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  73828. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  73829. /**
  73830. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  73831. */
  73832. var PoseEnabledControllerHelper = /** @class */ (function () {
  73833. function PoseEnabledControllerHelper() {
  73834. }
  73835. /**
  73836. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  73837. * @param vrGamepad the gamepad to initialized
  73838. * @returns a vr controller of the type the gamepad identified as
  73839. */
  73840. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  73841. // Oculus Touch
  73842. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  73843. return new BABYLON.OculusTouchController(vrGamepad);
  73844. }
  73845. // Windows Mixed Reality controllers
  73846. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  73847. return new BABYLON.WindowsMotionController(vrGamepad);
  73848. }
  73849. // HTC Vive
  73850. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  73851. return new BABYLON.ViveController(vrGamepad);
  73852. }
  73853. // Samsung/Oculus Gear VR or Oculus Go
  73854. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  73855. return new BABYLON.GearVRController(vrGamepad);
  73856. }
  73857. // Google Daydream
  73858. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  73859. return new BABYLON.DaydreamController(vrGamepad);
  73860. }
  73861. // Generic
  73862. else {
  73863. return new BABYLON.GenericController(vrGamepad);
  73864. }
  73865. };
  73866. return PoseEnabledControllerHelper;
  73867. }());
  73868. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  73869. /**
  73870. * Defines the PoseEnabledController object that contains state of a vr capable controller
  73871. */
  73872. var PoseEnabledController = /** @class */ (function (_super) {
  73873. __extends(PoseEnabledController, _super);
  73874. /**
  73875. * Creates a new PoseEnabledController from a gamepad
  73876. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  73877. */
  73878. function PoseEnabledController(browserGamepad) {
  73879. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  73880. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  73881. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  73882. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  73883. /**
  73884. * The device position in babylon space
  73885. */
  73886. _this.devicePosition = BABYLON.Vector3.Zero();
  73887. /**
  73888. * The device rotation in babylon space
  73889. */
  73890. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  73891. /**
  73892. * The scale factor of the device in babylon space
  73893. */
  73894. _this.deviceScaleFactor = 1;
  73895. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  73896. /**
  73897. * Internal, matrix used to convert room space to babylon space
  73898. * @hidden
  73899. */
  73900. _this._deviceToWorld = BABYLON.Matrix.Identity();
  73901. /**
  73902. * Node to be used when casting a ray from the controller
  73903. * @hidden
  73904. */
  73905. _this._pointingPoseNode = null;
  73906. _this._workingMatrix = BABYLON.Matrix.Identity();
  73907. /**
  73908. * @hidden
  73909. */
  73910. _this._meshAttachedObservable = new BABYLON.Observable();
  73911. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  73912. _this.controllerType = PoseEnabledControllerType.GENERIC;
  73913. _this.position = BABYLON.Vector3.Zero();
  73914. _this.rotationQuaternion = new BABYLON.Quaternion();
  73915. _this._calculatedPosition = BABYLON.Vector3.Zero();
  73916. _this._calculatedRotation = new BABYLON.Quaternion();
  73917. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  73918. return _this;
  73919. }
  73920. /**
  73921. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  73922. */
  73923. PoseEnabledController.prototype.update = function () {
  73924. _super.prototype.update.call(this);
  73925. this._updatePoseAndMesh();
  73926. };
  73927. /**
  73928. * Updates only the pose device and mesh without doing any button event checking
  73929. */
  73930. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  73931. var pose = this.browserGamepad.pose;
  73932. this.updateFromDevice(pose);
  73933. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  73934. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  73935. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  73936. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  73937. if (this._mesh) {
  73938. this._mesh.position.copyFrom(this.devicePosition);
  73939. if (this._mesh.rotationQuaternion) {
  73940. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  73941. }
  73942. }
  73943. };
  73944. /**
  73945. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  73946. * @param poseData raw pose fromthe device
  73947. */
  73948. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  73949. if (poseData) {
  73950. this.rawPose = poseData;
  73951. if (poseData.position) {
  73952. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  73953. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  73954. this._deviceRoomPosition.z *= -1;
  73955. }
  73956. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  73957. this._calculatedPosition.addInPlace(this.position);
  73958. }
  73959. var pose = this.rawPose;
  73960. if (poseData.orientation && pose.orientation) {
  73961. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  73962. if (this._mesh) {
  73963. if (this._mesh.getScene().useRightHandedSystem) {
  73964. this._deviceRoomRotationQuaternion.z *= -1;
  73965. this._deviceRoomRotationQuaternion.w *= -1;
  73966. }
  73967. else {
  73968. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  73969. }
  73970. }
  73971. // if the camera is set, rotate to the camera's rotation
  73972. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  73973. }
  73974. }
  73975. };
  73976. /**
  73977. * Attaches a mesh to the controller
  73978. * @param mesh the mesh to be attached
  73979. */
  73980. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  73981. if (this._mesh) {
  73982. this._mesh.parent = null;
  73983. }
  73984. this._mesh = mesh;
  73985. if (this._poseControlledCamera) {
  73986. this._mesh.parent = this._poseControlledCamera;
  73987. }
  73988. if (!this._mesh.rotationQuaternion) {
  73989. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  73990. }
  73991. // 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
  73992. this._updatePoseAndMesh();
  73993. if (this._pointingPoseNode) {
  73994. var parents = [];
  73995. var obj = this._pointingPoseNode;
  73996. while (obj.parent) {
  73997. parents.push(obj.parent);
  73998. obj = obj.parent;
  73999. }
  74000. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  74001. }
  74002. this._meshAttachedObservable.notifyObservers(mesh);
  74003. };
  74004. /**
  74005. * Attaches the controllers mesh to a camera
  74006. * @param camera the camera the mesh should be attached to
  74007. */
  74008. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  74009. this._poseControlledCamera = camera;
  74010. if (this._mesh) {
  74011. this._mesh.parent = this._poseControlledCamera;
  74012. }
  74013. };
  74014. /**
  74015. * Disposes of the controller
  74016. */
  74017. PoseEnabledController.prototype.dispose = function () {
  74018. if (this._mesh) {
  74019. this._mesh.dispose();
  74020. }
  74021. this._mesh = null;
  74022. _super.prototype.dispose.call(this);
  74023. };
  74024. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  74025. /**
  74026. * The mesh that is attached to the controller
  74027. */
  74028. get: function () {
  74029. return this._mesh;
  74030. },
  74031. enumerable: true,
  74032. configurable: true
  74033. });
  74034. /**
  74035. * Gets the ray of the controller in the direction the controller is pointing
  74036. * @param length the length the resulting ray should be
  74037. * @returns a ray in the direction the controller is pointing
  74038. */
  74039. PoseEnabledController.prototype.getForwardRay = function (length) {
  74040. if (length === void 0) { length = 100; }
  74041. if (!this.mesh) {
  74042. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  74043. }
  74044. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  74045. var origin = m.getTranslation();
  74046. var forward = new BABYLON.Vector3(0, 0, -1);
  74047. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74048. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74049. return new BABYLON.Ray(origin, direction, length);
  74050. };
  74051. /**
  74052. * Name of the child mesh that can be used to cast a ray from the controller
  74053. */
  74054. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  74055. return PoseEnabledController;
  74056. }(BABYLON.Gamepad));
  74057. BABYLON.PoseEnabledController = PoseEnabledController;
  74058. })(BABYLON || (BABYLON = {}));
  74059. //# sourceMappingURL=babylon.poseEnabledController.js.map
  74060. var BABYLON;
  74061. (function (BABYLON) {
  74062. /**
  74063. * Defines the WebVRController object that represents controllers tracked in 3D space
  74064. */
  74065. var WebVRController = /** @class */ (function (_super) {
  74066. __extends(WebVRController, _super);
  74067. /**
  74068. * Creates a new WebVRController from a gamepad
  74069. * @param vrGamepad the gamepad that the WebVRController should be created from
  74070. */
  74071. function WebVRController(vrGamepad) {
  74072. var _this = _super.call(this, vrGamepad) || this;
  74073. // Observables
  74074. /**
  74075. * Fired when the trigger state has changed
  74076. */
  74077. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  74078. /**
  74079. * Fired when the main button state has changed
  74080. */
  74081. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  74082. /**
  74083. * Fired when the secondary button state has changed
  74084. */
  74085. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  74086. /**
  74087. * Fired when the pad state has changed
  74088. */
  74089. _this.onPadStateChangedObservable = new BABYLON.Observable();
  74090. /**
  74091. * Fired when controllers stick values have changed
  74092. */
  74093. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  74094. /**
  74095. * X and Y axis corrisponding to the controllers joystick
  74096. */
  74097. _this.pad = { x: 0, y: 0 };
  74098. // avoid GC, store state in a tmp object
  74099. _this._changes = {
  74100. pressChanged: false,
  74101. touchChanged: false,
  74102. valueChanged: false,
  74103. changed: false
  74104. };
  74105. _this._buttons = new Array(vrGamepad.buttons.length);
  74106. _this.hand = vrGamepad.hand;
  74107. return _this;
  74108. }
  74109. /**
  74110. * Fired when a controller button's state has changed
  74111. * @param callback the callback containing the button that was modified
  74112. */
  74113. WebVRController.prototype.onButtonStateChange = function (callback) {
  74114. this._onButtonStateChange = callback;
  74115. };
  74116. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  74117. /**
  74118. * The default controller model for the controller
  74119. */
  74120. get: function () {
  74121. return this._defaultModel;
  74122. },
  74123. enumerable: true,
  74124. configurable: true
  74125. });
  74126. /**
  74127. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  74128. */
  74129. WebVRController.prototype.update = function () {
  74130. _super.prototype.update.call(this);
  74131. for (var index = 0; index < this._buttons.length; index++) {
  74132. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  74133. }
  74134. ;
  74135. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  74136. this.pad.x = this.leftStick.x;
  74137. this.pad.y = this.leftStick.y;
  74138. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  74139. }
  74140. };
  74141. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  74142. if (!newState) {
  74143. newState = {
  74144. pressed: false,
  74145. touched: false,
  74146. value: 0
  74147. };
  74148. }
  74149. if (!currentState) {
  74150. this._buttons[buttonIndex] = {
  74151. pressed: newState.pressed,
  74152. touched: newState.touched,
  74153. value: newState.value
  74154. };
  74155. return;
  74156. }
  74157. this._checkChanges(newState, currentState);
  74158. if (this._changes.changed) {
  74159. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  74160. this._handleButtonChange(buttonIndex, newState, this._changes);
  74161. }
  74162. this._buttons[buttonIndex].pressed = newState.pressed;
  74163. this._buttons[buttonIndex].touched = newState.touched;
  74164. // oculus triggers are never 0, thou not touched.
  74165. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  74166. };
  74167. WebVRController.prototype._checkChanges = function (newState, currentState) {
  74168. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  74169. this._changes.touchChanged = newState.touched !== currentState.touched;
  74170. this._changes.valueChanged = newState.value !== currentState.value;
  74171. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  74172. return this._changes;
  74173. };
  74174. /**
  74175. * Disposes of th webVRCOntroller
  74176. */
  74177. WebVRController.prototype.dispose = function () {
  74178. _super.prototype.dispose.call(this);
  74179. this.onTriggerStateChangedObservable.clear();
  74180. this.onMainButtonStateChangedObservable.clear();
  74181. this.onSecondaryButtonStateChangedObservable.clear();
  74182. this.onPadStateChangedObservable.clear();
  74183. this.onPadValuesChangedObservable.clear();
  74184. };
  74185. return WebVRController;
  74186. }(BABYLON.PoseEnabledController));
  74187. BABYLON.WebVRController = WebVRController;
  74188. })(BABYLON || (BABYLON = {}));
  74189. //# sourceMappingURL=babylon.webVRController.js.map
  74190. var BABYLON;
  74191. (function (BABYLON) {
  74192. /**
  74193. * Oculus Touch Controller
  74194. */
  74195. var OculusTouchController = /** @class */ (function (_super) {
  74196. __extends(OculusTouchController, _super);
  74197. /**
  74198. * Creates a new OculusTouchController from a gamepad
  74199. * @param vrGamepad the gamepad that the controller should be created from
  74200. */
  74201. function OculusTouchController(vrGamepad) {
  74202. var _this = _super.call(this, vrGamepad) || this;
  74203. /**
  74204. * Fired when the secondary trigger on this controller is modified
  74205. */
  74206. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  74207. /**
  74208. * Fired when the thumb rest on this controller is modified
  74209. */
  74210. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  74211. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  74212. return _this;
  74213. }
  74214. /**
  74215. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74216. * @param scene scene in which to add meshes
  74217. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74218. */
  74219. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74220. var _this = this;
  74221. var meshName;
  74222. // Hand
  74223. if (this.hand === 'left') {
  74224. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  74225. }
  74226. else { // Right is the default if no hand is specified
  74227. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  74228. }
  74229. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  74230. /*
  74231. Parent Mesh name: oculus_touch_left
  74232. - body
  74233. - trigger
  74234. - thumbstick
  74235. - grip
  74236. - button_y
  74237. - button_x
  74238. - button_enter
  74239. */
  74240. _this._defaultModel = newMeshes[1];
  74241. _this.attachToMesh(_this._defaultModel);
  74242. if (meshLoaded) {
  74243. meshLoaded(_this._defaultModel);
  74244. }
  74245. });
  74246. };
  74247. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  74248. /**
  74249. * Fired when the A button on this controller is modified
  74250. */
  74251. get: function () {
  74252. if (this.hand === 'right') {
  74253. return this.onMainButtonStateChangedObservable;
  74254. }
  74255. else {
  74256. throw new Error('No A button on left hand');
  74257. }
  74258. },
  74259. enumerable: true,
  74260. configurable: true
  74261. });
  74262. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  74263. /**
  74264. * Fired when the B button on this controller is modified
  74265. */
  74266. get: function () {
  74267. if (this.hand === 'right') {
  74268. return this.onSecondaryButtonStateChangedObservable;
  74269. }
  74270. else {
  74271. throw new Error('No B button on left hand');
  74272. }
  74273. },
  74274. enumerable: true,
  74275. configurable: true
  74276. });
  74277. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  74278. /**
  74279. * Fired when the X button on this controller is modified
  74280. */
  74281. get: function () {
  74282. if (this.hand === 'left') {
  74283. return this.onMainButtonStateChangedObservable;
  74284. }
  74285. else {
  74286. throw new Error('No X button on right hand');
  74287. }
  74288. },
  74289. enumerable: true,
  74290. configurable: true
  74291. });
  74292. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  74293. /**
  74294. * Fired when the Y button on this controller is modified
  74295. */
  74296. get: function () {
  74297. if (this.hand === 'left') {
  74298. return this.onSecondaryButtonStateChangedObservable;
  74299. }
  74300. else {
  74301. throw new Error('No Y button on right hand');
  74302. }
  74303. },
  74304. enumerable: true,
  74305. configurable: true
  74306. });
  74307. /**
  74308. * Called once for each button that changed state since the last frame
  74309. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  74310. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  74311. * 2) secondary trigger (same)
  74312. * 3) A (right) X (left), touch, pressed = value
  74313. * 4) B / Y
  74314. * 5) thumb rest
  74315. * @param buttonIdx Which button index changed
  74316. * @param state New state of the button
  74317. * @param changes Which properties on the state changed since last frame
  74318. */
  74319. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74320. var notifyObject = state; //{ state: state, changes: changes };
  74321. var triggerDirection = this.hand === 'right' ? -1 : 1;
  74322. switch (buttonIdx) {
  74323. case 0:
  74324. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74325. return;
  74326. case 1: // index trigger
  74327. if (this._defaultModel) {
  74328. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  74329. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  74330. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  74331. }
  74332. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74333. return;
  74334. case 2: // secondary trigger
  74335. if (this._defaultModel) {
  74336. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  74337. }
  74338. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  74339. return;
  74340. case 3:
  74341. if (this._defaultModel) {
  74342. if (notifyObject.pressed) {
  74343. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  74344. }
  74345. else {
  74346. (this._defaultModel.getChildren()[1]).position.y = 0;
  74347. }
  74348. }
  74349. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74350. return;
  74351. case 4:
  74352. if (this._defaultModel) {
  74353. if (notifyObject.pressed) {
  74354. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74355. }
  74356. else {
  74357. (this._defaultModel.getChildren()[2]).position.y = 0;
  74358. }
  74359. }
  74360. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74361. return;
  74362. case 5:
  74363. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  74364. return;
  74365. }
  74366. };
  74367. /**
  74368. * Base Url for the controller model.
  74369. */
  74370. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  74371. /**
  74372. * File name for the left controller model.
  74373. */
  74374. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  74375. /**
  74376. * File name for the right controller model.
  74377. */
  74378. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  74379. return OculusTouchController;
  74380. }(BABYLON.WebVRController));
  74381. BABYLON.OculusTouchController = OculusTouchController;
  74382. })(BABYLON || (BABYLON = {}));
  74383. //# sourceMappingURL=babylon.oculusTouchController.js.map
  74384. var BABYLON;
  74385. (function (BABYLON) {
  74386. /**
  74387. * Vive Controller
  74388. */
  74389. var ViveController = /** @class */ (function (_super) {
  74390. __extends(ViveController, _super);
  74391. /**
  74392. * Creates a new ViveController from a gamepad
  74393. * @param vrGamepad the gamepad that the controller should be created from
  74394. */
  74395. function ViveController(vrGamepad) {
  74396. var _this = _super.call(this, vrGamepad) || this;
  74397. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  74398. _this._invertLeftStickY = true;
  74399. return _this;
  74400. }
  74401. /**
  74402. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74403. * @param scene scene in which to add meshes
  74404. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74405. */
  74406. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74407. var _this = this;
  74408. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  74409. /*
  74410. Parent Mesh name: ViveWand
  74411. - body
  74412. - r_gripper
  74413. - l_gripper
  74414. - menu_button
  74415. - system_button
  74416. - trackpad
  74417. - trigger
  74418. - LED
  74419. */
  74420. _this._defaultModel = newMeshes[1];
  74421. _this.attachToMesh(_this._defaultModel);
  74422. if (meshLoaded) {
  74423. meshLoaded(_this._defaultModel);
  74424. }
  74425. });
  74426. };
  74427. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  74428. /**
  74429. * Fired when the left button on this controller is modified
  74430. */
  74431. get: function () {
  74432. return this.onMainButtonStateChangedObservable;
  74433. },
  74434. enumerable: true,
  74435. configurable: true
  74436. });
  74437. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  74438. /**
  74439. * Fired when the right button on this controller is modified
  74440. */
  74441. get: function () {
  74442. return this.onMainButtonStateChangedObservable;
  74443. },
  74444. enumerable: true,
  74445. configurable: true
  74446. });
  74447. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  74448. /**
  74449. * Fired when the menu button on this controller is modified
  74450. */
  74451. get: function () {
  74452. return this.onSecondaryButtonStateChangedObservable;
  74453. },
  74454. enumerable: true,
  74455. configurable: true
  74456. });
  74457. /**
  74458. * Called once for each button that changed state since the last frame
  74459. * Vive mapping:
  74460. * 0: touchpad
  74461. * 1: trigger
  74462. * 2: left AND right buttons
  74463. * 3: menu button
  74464. * @param buttonIdx Which button index changed
  74465. * @param state New state of the button
  74466. * @param changes Which properties on the state changed since last frame
  74467. */
  74468. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74469. var notifyObject = state; //{ state: state, changes: changes };
  74470. switch (buttonIdx) {
  74471. case 0:
  74472. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74473. return;
  74474. case 1: // index trigger
  74475. if (this._defaultModel) {
  74476. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  74477. }
  74478. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74479. return;
  74480. case 2: // left AND right button
  74481. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74482. return;
  74483. case 3:
  74484. if (this._defaultModel) {
  74485. if (notifyObject.pressed) {
  74486. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74487. }
  74488. else {
  74489. (this._defaultModel.getChildren()[2]).position.y = 0;
  74490. }
  74491. }
  74492. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74493. return;
  74494. }
  74495. };
  74496. /**
  74497. * Base Url for the controller model.
  74498. */
  74499. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  74500. /**
  74501. * File name for the controller model.
  74502. */
  74503. ViveController.MODEL_FILENAME = 'wand.babylon';
  74504. return ViveController;
  74505. }(BABYLON.WebVRController));
  74506. BABYLON.ViveController = ViveController;
  74507. })(BABYLON || (BABYLON = {}));
  74508. //# sourceMappingURL=babylon.viveController.js.map
  74509. var BABYLON;
  74510. (function (BABYLON) {
  74511. /**
  74512. * Generic Controller
  74513. */
  74514. var GenericController = /** @class */ (function (_super) {
  74515. __extends(GenericController, _super);
  74516. /**
  74517. * Creates a new GenericController from a gamepad
  74518. * @param vrGamepad the gamepad that the controller should be created from
  74519. */
  74520. function GenericController(vrGamepad) {
  74521. return _super.call(this, vrGamepad) || this;
  74522. }
  74523. /**
  74524. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74525. * @param scene scene in which to add meshes
  74526. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74527. */
  74528. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74529. var _this = this;
  74530. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  74531. _this._defaultModel = newMeshes[1];
  74532. _this.attachToMesh(_this._defaultModel);
  74533. if (meshLoaded) {
  74534. meshLoaded(_this._defaultModel);
  74535. }
  74536. });
  74537. };
  74538. /**
  74539. * Called once for each button that changed state since the last frame
  74540. * @param buttonIdx Which button index changed
  74541. * @param state New state of the button
  74542. * @param changes Which properties on the state changed since last frame
  74543. */
  74544. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74545. console.log("Button id: " + buttonIdx + "state: ");
  74546. console.dir(state);
  74547. };
  74548. /**
  74549. * Base Url for the controller model.
  74550. */
  74551. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74552. /**
  74553. * File name for the controller model.
  74554. */
  74555. GenericController.MODEL_FILENAME = 'generic.babylon';
  74556. return GenericController;
  74557. }(BABYLON.WebVRController));
  74558. BABYLON.GenericController = GenericController;
  74559. })(BABYLON || (BABYLON = {}));
  74560. //# sourceMappingURL=babylon.genericController.js.map
  74561. var BABYLON;
  74562. (function (BABYLON) {
  74563. /**
  74564. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  74565. */
  74566. var LoadedMeshInfo = /** @class */ (function () {
  74567. function LoadedMeshInfo() {
  74568. /**
  74569. * Map of the button meshes contained in the controller
  74570. */
  74571. this.buttonMeshes = {};
  74572. /**
  74573. * Map of the axis meshes contained in the controller
  74574. */
  74575. this.axisMeshes = {};
  74576. }
  74577. return LoadedMeshInfo;
  74578. }());
  74579. /**
  74580. * Defines the WindowsMotionController object that the state of the windows motion controller
  74581. */
  74582. var WindowsMotionController = /** @class */ (function (_super) {
  74583. __extends(WindowsMotionController, _super);
  74584. /**
  74585. * Creates a new WindowsMotionController from a gamepad
  74586. * @param vrGamepad the gamepad that the controller should be created from
  74587. */
  74588. function WindowsMotionController(vrGamepad) {
  74589. var _this = _super.call(this, vrGamepad) || this;
  74590. _this._mapping = {
  74591. // Semantic button names
  74592. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  74593. // A mapping of the button name to glTF model node name
  74594. // that should be transformed by button value.
  74595. buttonMeshNames: {
  74596. 'trigger': 'SELECT',
  74597. 'menu': 'MENU',
  74598. 'grip': 'GRASP',
  74599. 'thumbstick': 'THUMBSTICK_PRESS',
  74600. 'trackpad': 'TOUCHPAD_PRESS'
  74601. },
  74602. // This mapping is used to translate from the Motion Controller to Babylon semantics
  74603. buttonObservableNames: {
  74604. 'trigger': 'onTriggerStateChangedObservable',
  74605. 'menu': 'onSecondaryButtonStateChangedObservable',
  74606. 'grip': 'onMainButtonStateChangedObservable',
  74607. 'thumbstick': 'onPadStateChangedObservable',
  74608. 'trackpad': 'onTrackpadChangedObservable'
  74609. },
  74610. // A mapping of the axis name to glTF model node name
  74611. // that should be transformed by axis value.
  74612. // This array mirrors the browserGamepad.axes array, such that
  74613. // the mesh corresponding to axis 0 is in this array index 0.
  74614. axisMeshNames: [
  74615. 'THUMBSTICK_X',
  74616. 'THUMBSTICK_Y',
  74617. 'TOUCHPAD_TOUCH_X',
  74618. 'TOUCHPAD_TOUCH_Y'
  74619. ],
  74620. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  74621. };
  74622. /**
  74623. * Fired when the trackpad on this controller is clicked
  74624. */
  74625. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  74626. /**
  74627. * Fired when the trackpad on this controller is modified
  74628. */
  74629. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  74630. /**
  74631. * The current x and y values of this controller's trackpad
  74632. */
  74633. _this.trackpad = { x: 0, y: 0 };
  74634. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  74635. _this._loadedMeshInfo = null;
  74636. return _this;
  74637. }
  74638. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  74639. /**
  74640. * Fired when the trigger on this controller is modified
  74641. */
  74642. get: function () {
  74643. return this.onTriggerStateChangedObservable;
  74644. },
  74645. enumerable: true,
  74646. configurable: true
  74647. });
  74648. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  74649. /**
  74650. * Fired when the menu button on this controller is modified
  74651. */
  74652. get: function () {
  74653. return this.onSecondaryButtonStateChangedObservable;
  74654. },
  74655. enumerable: true,
  74656. configurable: true
  74657. });
  74658. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  74659. /**
  74660. * Fired when the grip button on this controller is modified
  74661. */
  74662. get: function () {
  74663. return this.onMainButtonStateChangedObservable;
  74664. },
  74665. enumerable: true,
  74666. configurable: true
  74667. });
  74668. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  74669. /**
  74670. * Fired when the thumbstick button on this controller is modified
  74671. */
  74672. get: function () {
  74673. return this.onPadStateChangedObservable;
  74674. },
  74675. enumerable: true,
  74676. configurable: true
  74677. });
  74678. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  74679. /**
  74680. * Fired when the touchpad button on this controller is modified
  74681. */
  74682. get: function () {
  74683. return this.onTrackpadChangedObservable;
  74684. },
  74685. enumerable: true,
  74686. configurable: true
  74687. });
  74688. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  74689. /**
  74690. * Fired when the touchpad values on this controller are modified
  74691. */
  74692. get: function () {
  74693. return this.onTrackpadValuesChangedObservable;
  74694. },
  74695. enumerable: true,
  74696. configurable: true
  74697. });
  74698. WindowsMotionController.prototype._updateTrackpad = function () {
  74699. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  74700. this.trackpad.x = this.browserGamepad["axes"][2];
  74701. this.trackpad.y = this.browserGamepad["axes"][3];
  74702. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  74703. }
  74704. };
  74705. /**
  74706. * Called once per frame by the engine.
  74707. */
  74708. WindowsMotionController.prototype.update = function () {
  74709. _super.prototype.update.call(this);
  74710. if (this.browserGamepad.axes) {
  74711. this._updateTrackpad();
  74712. // Only need to animate axes if there is a loaded mesh
  74713. if (this._loadedMeshInfo) {
  74714. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  74715. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  74716. }
  74717. }
  74718. }
  74719. };
  74720. /**
  74721. * Called once for each button that changed state since the last frame
  74722. * @param buttonIdx Which button index changed
  74723. * @param state New state of the button
  74724. * @param changes Which properties on the state changed since last frame
  74725. */
  74726. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74727. var buttonName = this._mapping.buttons[buttonIdx];
  74728. if (!buttonName) {
  74729. return;
  74730. }
  74731. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  74732. this._updateTrackpad();
  74733. // Only emit events for buttons that we know how to map from index to name
  74734. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  74735. if (observable) {
  74736. observable.notifyObservers(state);
  74737. }
  74738. this._lerpButtonTransform(buttonName, state.value);
  74739. };
  74740. /**
  74741. * Moves the buttons on the controller mesh based on their current state
  74742. * @param buttonName the name of the button to move
  74743. * @param buttonValue the value of the button which determines the buttons new position
  74744. */
  74745. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  74746. // If there is no loaded mesh, there is nothing to transform.
  74747. if (!this._loadedMeshInfo) {
  74748. return;
  74749. }
  74750. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  74751. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  74752. return;
  74753. }
  74754. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  74755. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  74756. };
  74757. /**
  74758. * Moves the axis on the controller mesh based on its current state
  74759. * @param axis the index of the axis
  74760. * @param axisValue the value of the axis which determines the meshes new position
  74761. * @hidden
  74762. */
  74763. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  74764. if (!this._loadedMeshInfo) {
  74765. return;
  74766. }
  74767. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  74768. if (!meshInfo) {
  74769. return;
  74770. }
  74771. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  74772. return;
  74773. }
  74774. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  74775. var lerpValue = axisValue * 0.5 + 0.5;
  74776. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  74777. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  74778. };
  74779. /**
  74780. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74781. * @param scene scene in which to add meshes
  74782. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74783. */
  74784. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  74785. var _this = this;
  74786. if (forceDefault === void 0) { forceDefault = false; }
  74787. var path;
  74788. var filename;
  74789. // Checking if GLB loader is present
  74790. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  74791. // Determine the device specific folder based on the ID suffix
  74792. var device = 'default';
  74793. if (this.id && !forceDefault) {
  74794. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  74795. device = ((match && match[0]) || device);
  74796. }
  74797. // Hand
  74798. if (this.hand === 'left') {
  74799. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  74800. }
  74801. else { // Right is the default if no hand is specified
  74802. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  74803. }
  74804. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  74805. }
  74806. else {
  74807. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  74808. path = BABYLON.GenericController.MODEL_BASE_URL;
  74809. filename = BABYLON.GenericController.MODEL_FILENAME;
  74810. }
  74811. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  74812. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  74813. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  74814. if (!_this._loadedMeshInfo) {
  74815. return;
  74816. }
  74817. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  74818. _this.attachToMesh(_this._defaultModel);
  74819. if (meshLoaded) {
  74820. meshLoaded(_this._defaultModel);
  74821. }
  74822. }, null, function (scene, message) {
  74823. BABYLON.Tools.Log(message);
  74824. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  74825. if (!forceDefault) {
  74826. _this.initControllerMesh(scene, meshLoaded, true);
  74827. }
  74828. });
  74829. };
  74830. /**
  74831. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  74832. * can be transformed by button presses and axes values, based on this._mapping.
  74833. *
  74834. * @param scene scene in which the meshes exist
  74835. * @param meshes list of meshes that make up the controller model to process
  74836. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  74837. */
  74838. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  74839. var loadedMeshInfo = null;
  74840. // Create a new mesh to contain the glTF hierarchy
  74841. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  74842. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  74843. var childMesh = null;
  74844. for (var i = 0; i < meshes.length; i++) {
  74845. var mesh = meshes[i];
  74846. if (!mesh.parent) {
  74847. // Exclude controller meshes from picking results
  74848. mesh.isPickable = false;
  74849. // Handle root node, attach to the new parentMesh
  74850. childMesh = mesh;
  74851. break;
  74852. }
  74853. }
  74854. if (childMesh) {
  74855. childMesh.setParent(parentMesh);
  74856. // Create our mesh info. Note that this method will always return non-null.
  74857. loadedMeshInfo = this.createMeshInfo(parentMesh);
  74858. }
  74859. else {
  74860. BABYLON.Tools.Warn('Could not find root node in model file.');
  74861. }
  74862. return loadedMeshInfo;
  74863. };
  74864. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  74865. var loadedMeshInfo = new LoadedMeshInfo();
  74866. var i;
  74867. loadedMeshInfo.rootNode = rootNode;
  74868. // Reset the caches
  74869. loadedMeshInfo.buttonMeshes = {};
  74870. loadedMeshInfo.axisMeshes = {};
  74871. // Button Meshes
  74872. for (i = 0; i < this._mapping.buttons.length; i++) {
  74873. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  74874. if (!buttonMeshName) {
  74875. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  74876. continue;
  74877. }
  74878. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  74879. if (!buttonMesh) {
  74880. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  74881. continue;
  74882. }
  74883. var buttonMeshInfo = {
  74884. index: i,
  74885. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  74886. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  74887. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  74888. };
  74889. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  74890. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  74891. }
  74892. else {
  74893. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  74894. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  74895. '(VALUE: ' + !!buttonMeshInfo.value +
  74896. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  74897. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  74898. ')');
  74899. }
  74900. }
  74901. // Axis Meshes
  74902. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  74903. var axisMeshName = this._mapping.axisMeshNames[i];
  74904. if (!axisMeshName) {
  74905. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  74906. continue;
  74907. }
  74908. var axisMesh = getChildByName(rootNode, axisMeshName);
  74909. if (!axisMesh) {
  74910. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  74911. continue;
  74912. }
  74913. var axisMeshInfo = {
  74914. index: i,
  74915. value: getImmediateChildByName(axisMesh, 'VALUE'),
  74916. min: getImmediateChildByName(axisMesh, 'MIN'),
  74917. max: getImmediateChildByName(axisMesh, 'MAX')
  74918. };
  74919. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  74920. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  74921. }
  74922. else {
  74923. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  74924. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  74925. '(VALUE: ' + !!axisMeshInfo.value +
  74926. ', MIN: ' + !!axisMeshInfo.min +
  74927. ', MAX:' + !!axisMeshInfo.max +
  74928. ')');
  74929. }
  74930. }
  74931. // Pointing Ray
  74932. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  74933. if (!loadedMeshInfo.pointingPoseNode) {
  74934. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  74935. }
  74936. else {
  74937. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  74938. }
  74939. return loadedMeshInfo;
  74940. // Look through all children recursively. This will return null if no mesh exists with the given name.
  74941. function getChildByName(node, name) {
  74942. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  74943. }
  74944. // Look through only immediate children. This will return null if no mesh exists with the given name.
  74945. function getImmediateChildByName(node, name) {
  74946. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  74947. }
  74948. };
  74949. /**
  74950. * Gets the ray of the controller in the direction the controller is pointing
  74951. * @param length the length the resulting ray should be
  74952. * @returns a ray in the direction the controller is pointing
  74953. */
  74954. WindowsMotionController.prototype.getForwardRay = function (length) {
  74955. if (length === void 0) { length = 100; }
  74956. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  74957. return _super.prototype.getForwardRay.call(this, length);
  74958. }
  74959. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  74960. var origin = m.getTranslation();
  74961. var forward = new BABYLON.Vector3(0, 0, -1);
  74962. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74963. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74964. return new BABYLON.Ray(origin, direction, length);
  74965. };
  74966. /**
  74967. * Disposes of the controller
  74968. */
  74969. WindowsMotionController.prototype.dispose = function () {
  74970. _super.prototype.dispose.call(this);
  74971. this.onTrackpadChangedObservable.clear();
  74972. };
  74973. /**
  74974. * The base url used to load the left and right controller models
  74975. */
  74976. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  74977. /**
  74978. * The name of the left controller model file
  74979. */
  74980. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  74981. /**
  74982. * The name of the right controller model file
  74983. */
  74984. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  74985. /**
  74986. * The controller name prefix for this controller type
  74987. */
  74988. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  74989. /**
  74990. * The controller id pattern for this controller type
  74991. */
  74992. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  74993. return WindowsMotionController;
  74994. }(BABYLON.WebVRController));
  74995. BABYLON.WindowsMotionController = WindowsMotionController;
  74996. })(BABYLON || (BABYLON = {}));
  74997. //# sourceMappingURL=babylon.windowsMotionController.js.map
  74998. var BABYLON;
  74999. (function (BABYLON) {
  75000. /**
  75001. * Gear VR Controller
  75002. */
  75003. var GearVRController = /** @class */ (function (_super) {
  75004. __extends(GearVRController, _super);
  75005. /**
  75006. * Creates a new GearVRController from a gamepad
  75007. * @param vrGamepad the gamepad that the controller should be created from
  75008. */
  75009. function GearVRController(vrGamepad) {
  75010. var _this = _super.call(this, vrGamepad) || this;
  75011. _this._maxRotationDistFromHeadset = Math.PI / 5;
  75012. _this._draggedRoomRotation = 0;
  75013. _this._tmpVector = new BABYLON.Vector3();
  75014. _this._buttonIndexToObservableNameMap = [
  75015. 'onTrackpadChangedObservable',
  75016. 'onTriggerStateChangedObservable' // Trigger
  75017. ];
  75018. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  75019. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  75020. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  75021. return _this;
  75022. }
  75023. /**
  75024. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75025. * @param poseData raw pose fromthe device
  75026. */
  75027. GearVRController.prototype.updateFromDevice = function (poseData) {
  75028. _super.prototype.updateFromDevice.call(this, poseData);
  75029. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  75030. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  75031. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  75032. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  75033. // Find the radian distance away that the headset is from the controllers rotation
  75034. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  75035. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  75036. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  75037. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  75038. this._draggedRoomRotation += rotationAmount;
  75039. // Rotate controller around headset
  75040. var sin = Math.sin(-rotationAmount);
  75041. var cos = Math.cos(-rotationAmount);
  75042. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  75043. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  75044. }
  75045. }
  75046. }
  75047. };
  75048. /**
  75049. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75050. * @param scene scene in which to add meshes
  75051. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75052. */
  75053. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75054. var _this = this;
  75055. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  75056. // Offset the controller so it will rotate around the users wrist
  75057. var mesh = new BABYLON.Mesh("", scene);
  75058. newMeshes[1].parent = mesh;
  75059. newMeshes[1].position.z = -0.15;
  75060. _this._defaultModel = mesh;
  75061. _this.attachToMesh(_this._defaultModel);
  75062. if (meshLoaded) {
  75063. meshLoaded(_this._defaultModel);
  75064. }
  75065. });
  75066. };
  75067. /**
  75068. * Called once for each button that changed state since the last frame
  75069. * @param buttonIdx Which button index changed
  75070. * @param state New state of the button
  75071. * @param changes Which properties on the state changed since last frame
  75072. */
  75073. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75074. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  75075. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  75076. // Only emit events for buttons that we know how to map from index to observable
  75077. var observable = this[observableName];
  75078. if (observable) {
  75079. observable.notifyObservers(state);
  75080. }
  75081. }
  75082. };
  75083. /**
  75084. * Base Url for the controller model.
  75085. */
  75086. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75087. /**
  75088. * File name for the controller model.
  75089. */
  75090. GearVRController.MODEL_FILENAME = 'generic.babylon';
  75091. /**
  75092. * Gamepad Id prefix used to identify this controller.
  75093. */
  75094. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  75095. return GearVRController;
  75096. }(BABYLON.WebVRController));
  75097. BABYLON.GearVRController = GearVRController;
  75098. })(BABYLON || (BABYLON = {}));
  75099. //# sourceMappingURL=babylon.gearVRController.js.map
  75100. var BABYLON;
  75101. (function (BABYLON) {
  75102. /**
  75103. * Google Daydream controller
  75104. */
  75105. var DaydreamController = /** @class */ (function (_super) {
  75106. __extends(DaydreamController, _super);
  75107. /**
  75108. * Creates a new DaydreamController from a gamepad
  75109. * @param vrGamepad the gamepad that the controller should be created from
  75110. */
  75111. function DaydreamController(vrGamepad) {
  75112. var _this = _super.call(this, vrGamepad) || this;
  75113. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  75114. return _this;
  75115. }
  75116. /**
  75117. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75118. * @param scene scene in which to add meshes
  75119. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75120. */
  75121. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75122. var _this = this;
  75123. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  75124. _this._defaultModel = newMeshes[1];
  75125. _this.attachToMesh(_this._defaultModel);
  75126. if (meshLoaded) {
  75127. meshLoaded(_this._defaultModel);
  75128. }
  75129. });
  75130. };
  75131. /**
  75132. * Called once for each button that changed state since the last frame
  75133. * @param buttonIdx Which button index changed
  75134. * @param state New state of the button
  75135. * @param changes Which properties on the state changed since last frame
  75136. */
  75137. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75138. // Daydream controller only has 1 GamepadButton (on the trackpad).
  75139. if (buttonIdx === 0) {
  75140. var observable = this.onTriggerStateChangedObservable;
  75141. if (observable) {
  75142. observable.notifyObservers(state);
  75143. }
  75144. }
  75145. else {
  75146. // If the app or home buttons are ever made available
  75147. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  75148. }
  75149. };
  75150. /**
  75151. * Base Url for the controller model.
  75152. */
  75153. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75154. /**
  75155. * File name for the controller model.
  75156. */
  75157. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  75158. /**
  75159. * Gamepad Id prefix used to identify Daydream Controller.
  75160. */
  75161. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  75162. return DaydreamController;
  75163. }(BABYLON.WebVRController));
  75164. BABYLON.DaydreamController = DaydreamController;
  75165. })(BABYLON || (BABYLON = {}));
  75166. //# sourceMappingURL=babylon.daydreamController.js.map
  75167. var BABYLON;
  75168. (function (BABYLON) {
  75169. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  75170. get: function () {
  75171. if (!this._gamepadManager) {
  75172. this._gamepadManager = new BABYLON.GamepadManager(this);
  75173. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  75174. if (!component) {
  75175. component = new GamepadSystemSceneComponent(this);
  75176. this._addComponent(component);
  75177. }
  75178. }
  75179. return this._gamepadManager;
  75180. },
  75181. enumerable: true,
  75182. configurable: true
  75183. });
  75184. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  75185. this.add(new BABYLON.FreeCameraGamepadInput());
  75186. return this;
  75187. };
  75188. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  75189. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  75190. return this;
  75191. };
  75192. /**
  75193. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  75194. */
  75195. var GamepadSystemSceneComponent = /** @class */ (function () {
  75196. /**
  75197. * Creates a new instance of the component for the given scene
  75198. * @param scene Defines the scene to register the component in
  75199. */
  75200. function GamepadSystemSceneComponent(scene) {
  75201. /**
  75202. * The component name helpfull to identify the component in the list of scene components.
  75203. */
  75204. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  75205. this.scene = scene;
  75206. }
  75207. /**
  75208. * Registers the component in a given scene
  75209. */
  75210. GamepadSystemSceneComponent.prototype.register = function () {
  75211. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  75212. };
  75213. /**
  75214. * Rebuilds the elements related to this component in case of
  75215. * context lost for instance.
  75216. */
  75217. GamepadSystemSceneComponent.prototype.rebuild = function () {
  75218. // Nothing to do for gamepads
  75219. };
  75220. /**
  75221. * Disposes the component and the associated ressources
  75222. */
  75223. GamepadSystemSceneComponent.prototype.dispose = function () {
  75224. var gamepadManager = this.scene._gamepadManager;
  75225. if (gamepadManager) {
  75226. gamepadManager.dispose();
  75227. this.scene._gamepadManager = null;
  75228. }
  75229. };
  75230. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  75231. var gamepadManager = this.scene._gamepadManager;
  75232. if (gamepadManager && gamepadManager._isMonitoring) {
  75233. gamepadManager._checkGamepadsStatus();
  75234. }
  75235. };
  75236. return GamepadSystemSceneComponent;
  75237. }());
  75238. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  75239. })(BABYLON || (BABYLON = {}));
  75240. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  75241. var BABYLON;
  75242. (function (BABYLON) {
  75243. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  75244. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  75245. });
  75246. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  75247. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  75248. });
  75249. var FollowCamera = /** @class */ (function (_super) {
  75250. __extends(FollowCamera, _super);
  75251. function FollowCamera(name, position, scene, lockedTarget) {
  75252. if (lockedTarget === void 0) { lockedTarget = null; }
  75253. var _this = _super.call(this, name, position, scene) || this;
  75254. _this.radius = 12;
  75255. _this.rotationOffset = 0;
  75256. _this.heightOffset = 4;
  75257. _this.cameraAcceleration = 0.05;
  75258. _this.maxCameraSpeed = 20;
  75259. _this.lockedTarget = lockedTarget;
  75260. return _this;
  75261. }
  75262. FollowCamera.prototype.getRadians = function (degrees) {
  75263. return degrees * Math.PI / 180;
  75264. };
  75265. FollowCamera.prototype.follow = function (cameraTarget) {
  75266. if (!cameraTarget)
  75267. return;
  75268. var yRotation;
  75269. if (cameraTarget.rotationQuaternion) {
  75270. var rotMatrix = new BABYLON.Matrix();
  75271. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  75272. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  75273. }
  75274. else {
  75275. yRotation = cameraTarget.rotation.y;
  75276. }
  75277. var radians = this.getRadians(this.rotationOffset) + yRotation;
  75278. var targetPosition = cameraTarget.getAbsolutePosition();
  75279. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  75280. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  75281. var dx = targetX - this.position.x;
  75282. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  75283. var dz = (targetZ) - this.position.z;
  75284. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  75285. var vy = dy * this.cameraAcceleration;
  75286. var vz = dz * this.cameraAcceleration * 2;
  75287. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  75288. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75289. }
  75290. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  75291. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75292. }
  75293. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  75294. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75295. }
  75296. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  75297. this.setTarget(targetPosition);
  75298. };
  75299. /** @hidden */
  75300. FollowCamera.prototype._checkInputs = function () {
  75301. _super.prototype._checkInputs.call(this);
  75302. if (this.lockedTarget) {
  75303. this.follow(this.lockedTarget);
  75304. }
  75305. };
  75306. FollowCamera.prototype.getClassName = function () {
  75307. return "FollowCamera";
  75308. };
  75309. __decorate([
  75310. BABYLON.serialize()
  75311. ], FollowCamera.prototype, "radius", void 0);
  75312. __decorate([
  75313. BABYLON.serialize()
  75314. ], FollowCamera.prototype, "rotationOffset", void 0);
  75315. __decorate([
  75316. BABYLON.serialize()
  75317. ], FollowCamera.prototype, "heightOffset", void 0);
  75318. __decorate([
  75319. BABYLON.serialize()
  75320. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  75321. __decorate([
  75322. BABYLON.serialize()
  75323. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  75324. __decorate([
  75325. BABYLON.serializeAsMeshReference("lockedTargetId")
  75326. ], FollowCamera.prototype, "lockedTarget", void 0);
  75327. return FollowCamera;
  75328. }(BABYLON.TargetCamera));
  75329. BABYLON.FollowCamera = FollowCamera;
  75330. var ArcFollowCamera = /** @class */ (function (_super) {
  75331. __extends(ArcFollowCamera, _super);
  75332. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  75333. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  75334. _this.alpha = alpha;
  75335. _this.beta = beta;
  75336. _this.radius = radius;
  75337. _this.target = target;
  75338. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  75339. _this.follow();
  75340. return _this;
  75341. }
  75342. ArcFollowCamera.prototype.follow = function () {
  75343. if (!this.target) {
  75344. return;
  75345. }
  75346. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  75347. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  75348. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  75349. var targetPosition = this.target.getAbsolutePosition();
  75350. this.position = targetPosition.add(this._cartesianCoordinates);
  75351. this.setTarget(targetPosition);
  75352. };
  75353. /** @hidden */
  75354. ArcFollowCamera.prototype._checkInputs = function () {
  75355. _super.prototype._checkInputs.call(this);
  75356. this.follow();
  75357. };
  75358. ArcFollowCamera.prototype.getClassName = function () {
  75359. return "ArcFollowCamera";
  75360. };
  75361. return ArcFollowCamera;
  75362. }(BABYLON.TargetCamera));
  75363. BABYLON.ArcFollowCamera = ArcFollowCamera;
  75364. })(BABYLON || (BABYLON = {}));
  75365. //# sourceMappingURL=babylon.followCamera.js.map
  75366. var BABYLON;
  75367. (function (BABYLON) {
  75368. // We're mainly based on the logic defined into the FreeCamera code
  75369. var UniversalCamera = /** @class */ (function (_super) {
  75370. __extends(UniversalCamera, _super);
  75371. //-- end properties for backward compatibility for inputs
  75372. function UniversalCamera(name, position, scene) {
  75373. var _this = _super.call(this, name, position, scene) || this;
  75374. _this.inputs.addGamepad();
  75375. return _this;
  75376. }
  75377. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  75378. //-- Begin properties for backward compatibility for inputs
  75379. get: function () {
  75380. var gamepad = this.inputs.attached["gamepad"];
  75381. if (gamepad)
  75382. return gamepad.gamepadAngularSensibility;
  75383. return 0;
  75384. },
  75385. set: function (value) {
  75386. var gamepad = this.inputs.attached["gamepad"];
  75387. if (gamepad)
  75388. gamepad.gamepadAngularSensibility = value;
  75389. },
  75390. enumerable: true,
  75391. configurable: true
  75392. });
  75393. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  75394. get: function () {
  75395. var gamepad = this.inputs.attached["gamepad"];
  75396. if (gamepad)
  75397. return gamepad.gamepadMoveSensibility;
  75398. return 0;
  75399. },
  75400. set: function (value) {
  75401. var gamepad = this.inputs.attached["gamepad"];
  75402. if (gamepad)
  75403. gamepad.gamepadMoveSensibility = value;
  75404. },
  75405. enumerable: true,
  75406. configurable: true
  75407. });
  75408. UniversalCamera.prototype.getClassName = function () {
  75409. return "UniversalCamera";
  75410. };
  75411. return UniversalCamera;
  75412. }(BABYLON.TouchCamera));
  75413. BABYLON.UniversalCamera = UniversalCamera;
  75414. })(BABYLON || (BABYLON = {}));
  75415. //# sourceMappingURL=babylon.universalCamera.js.map
  75416. var BABYLON;
  75417. (function (BABYLON) {
  75418. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  75419. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  75420. });
  75421. // We're mainly based on the logic defined into the FreeCamera code
  75422. var GamepadCamera = /** @class */ (function (_super) {
  75423. __extends(GamepadCamera, _super);
  75424. //-- end properties for backward compatibility for inputs
  75425. function GamepadCamera(name, position, scene) {
  75426. return _super.call(this, name, position, scene) || this;
  75427. }
  75428. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  75429. //-- Begin properties for backward compatibility for inputs
  75430. get: function () {
  75431. var gamepad = this.inputs.attached["gamepad"];
  75432. if (gamepad)
  75433. return gamepad.gamepadAngularSensibility;
  75434. return 0;
  75435. },
  75436. set: function (value) {
  75437. var gamepad = this.inputs.attached["gamepad"];
  75438. if (gamepad)
  75439. gamepad.gamepadAngularSensibility = value;
  75440. },
  75441. enumerable: true,
  75442. configurable: true
  75443. });
  75444. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  75445. get: function () {
  75446. var gamepad = this.inputs.attached["gamepad"];
  75447. if (gamepad)
  75448. return gamepad.gamepadMoveSensibility;
  75449. return 0;
  75450. },
  75451. set: function (value) {
  75452. var gamepad = this.inputs.attached["gamepad"];
  75453. if (gamepad)
  75454. gamepad.gamepadMoveSensibility = value;
  75455. },
  75456. enumerable: true,
  75457. configurable: true
  75458. });
  75459. GamepadCamera.prototype.getClassName = function () {
  75460. return "GamepadCamera";
  75461. };
  75462. return GamepadCamera;
  75463. }(BABYLON.UniversalCamera));
  75464. BABYLON.GamepadCamera = GamepadCamera;
  75465. })(BABYLON || (BABYLON = {}));
  75466. //# sourceMappingURL=babylon.gamepadCamera.js.map
  75467. var BABYLON;
  75468. (function (BABYLON) {
  75469. var PostProcessRenderPipelineManager = /** @class */ (function () {
  75470. function PostProcessRenderPipelineManager() {
  75471. this._renderPipelines = {};
  75472. }
  75473. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  75474. this._renderPipelines[renderPipeline._name] = renderPipeline;
  75475. };
  75476. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  75477. if (unique === void 0) { unique = false; }
  75478. var renderPipeline = this._renderPipelines[renderPipelineName];
  75479. if (!renderPipeline) {
  75480. return;
  75481. }
  75482. renderPipeline._attachCameras(cameras, unique);
  75483. };
  75484. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  75485. var renderPipeline = this._renderPipelines[renderPipelineName];
  75486. if (!renderPipeline) {
  75487. return;
  75488. }
  75489. renderPipeline._detachCameras(cameras);
  75490. };
  75491. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75492. var renderPipeline = this._renderPipelines[renderPipelineName];
  75493. if (!renderPipeline) {
  75494. return;
  75495. }
  75496. renderPipeline._enableEffect(renderEffectName, cameras);
  75497. };
  75498. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75499. var renderPipeline = this._renderPipelines[renderPipelineName];
  75500. if (!renderPipeline) {
  75501. return;
  75502. }
  75503. renderPipeline._disableEffect(renderEffectName, cameras);
  75504. };
  75505. PostProcessRenderPipelineManager.prototype.update = function () {
  75506. for (var renderPipelineName in this._renderPipelines) {
  75507. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75508. var pipeline = this._renderPipelines[renderPipelineName];
  75509. if (!pipeline.isSupported) {
  75510. pipeline.dispose();
  75511. delete this._renderPipelines[renderPipelineName];
  75512. }
  75513. else {
  75514. pipeline._update();
  75515. }
  75516. }
  75517. }
  75518. };
  75519. /** @hidden */
  75520. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  75521. for (var renderPipelineName in this._renderPipelines) {
  75522. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75523. var pipeline = this._renderPipelines[renderPipelineName];
  75524. pipeline._rebuild();
  75525. }
  75526. }
  75527. };
  75528. PostProcessRenderPipelineManager.prototype.dispose = function () {
  75529. for (var renderPipelineName in this._renderPipelines) {
  75530. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75531. var pipeline = this._renderPipelines[renderPipelineName];
  75532. pipeline.dispose();
  75533. }
  75534. }
  75535. };
  75536. return PostProcessRenderPipelineManager;
  75537. }());
  75538. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  75539. })(BABYLON || (BABYLON = {}));
  75540. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  75541. var BABYLON;
  75542. (function (BABYLON) {
  75543. /**
  75544. * This represents a set of one or more post processes in Babylon.
  75545. * A post process can be used to apply a shader to a texture after it is rendered.
  75546. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  75547. */
  75548. var PostProcessRenderEffect = /** @class */ (function () {
  75549. /**
  75550. * Instantiates a post process render effect.
  75551. * A post process can be used to apply a shader to a texture after it is rendered.
  75552. * @param engine The engine the effect is tied to
  75553. * @param name The name of the effect
  75554. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  75555. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  75556. */
  75557. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  75558. this._name = name;
  75559. this._singleInstance = singleInstance || true;
  75560. this._getPostProcesses = getPostProcesses;
  75561. this._cameras = {};
  75562. this._indicesForCamera = {};
  75563. this._postProcesses = {};
  75564. }
  75565. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  75566. /**
  75567. * Checks if all the post processes in the effect are supported.
  75568. */
  75569. get: function () {
  75570. for (var index in this._postProcesses) {
  75571. if (this._postProcesses.hasOwnProperty(index)) {
  75572. var pps = this._postProcesses[index];
  75573. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  75574. if (!pps[ppIndex].isSupported) {
  75575. return false;
  75576. }
  75577. }
  75578. }
  75579. }
  75580. return true;
  75581. },
  75582. enumerable: true,
  75583. configurable: true
  75584. });
  75585. /**
  75586. * Updates the current state of the effect
  75587. * @hidden
  75588. */
  75589. PostProcessRenderEffect.prototype._update = function () {
  75590. };
  75591. /**
  75592. * Attaches the effect on cameras
  75593. * @param cameras The camera to attach to.
  75594. * @hidden
  75595. */
  75596. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  75597. var _this = this;
  75598. var cameraKey;
  75599. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75600. if (!cams) {
  75601. return;
  75602. }
  75603. for (var i = 0; i < cams.length; i++) {
  75604. var camera = cams[i];
  75605. var cameraName = camera.name;
  75606. if (this._singleInstance) {
  75607. cameraKey = 0;
  75608. }
  75609. else {
  75610. cameraKey = cameraName;
  75611. }
  75612. if (!this._postProcesses[cameraKey]) {
  75613. var postProcess = this._getPostProcesses();
  75614. if (postProcess) {
  75615. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  75616. }
  75617. }
  75618. if (!this._indicesForCamera[cameraName]) {
  75619. this._indicesForCamera[cameraName] = [];
  75620. }
  75621. this._postProcesses[cameraKey].forEach(function (postProcess) {
  75622. var index = camera.attachPostProcess(postProcess);
  75623. _this._indicesForCamera[cameraName].push(index);
  75624. });
  75625. if (!this._cameras[cameraName]) {
  75626. this._cameras[cameraName] = camera;
  75627. }
  75628. }
  75629. };
  75630. /**
  75631. * Detatches the effect on cameras
  75632. * @param cameras The camera to detatch from.
  75633. * @hidden
  75634. */
  75635. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  75636. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75637. if (!cams) {
  75638. return;
  75639. }
  75640. for (var i = 0; i < cams.length; i++) {
  75641. var camera = cams[i];
  75642. var cameraName = camera.name;
  75643. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75644. camera.detachPostProcess(postProcess);
  75645. });
  75646. if (this._cameras[cameraName]) {
  75647. //this._indicesForCamera.splice(index, 1);
  75648. this._cameras[cameraName] = null;
  75649. }
  75650. }
  75651. };
  75652. /**
  75653. * Enables the effect on given cameras
  75654. * @param cameras The camera to enable.
  75655. * @hidden
  75656. */
  75657. PostProcessRenderEffect.prototype._enable = function (cameras) {
  75658. var _this = this;
  75659. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75660. if (!cams) {
  75661. return;
  75662. }
  75663. for (var i = 0; i < cams.length; i++) {
  75664. var camera = cams[i];
  75665. var cameraName = camera.name;
  75666. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  75667. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  75668. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75669. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  75670. });
  75671. }
  75672. }
  75673. }
  75674. };
  75675. /**
  75676. * Disables the effect on the given cameras
  75677. * @param cameras The camera to disable.
  75678. * @hidden
  75679. */
  75680. PostProcessRenderEffect.prototype._disable = function (cameras) {
  75681. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75682. if (!cams) {
  75683. return;
  75684. }
  75685. for (var i = 0; i < cams.length; i++) {
  75686. var camera = cams[i];
  75687. var cameraName = camera.name;
  75688. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75689. camera.detachPostProcess(postProcess);
  75690. });
  75691. }
  75692. };
  75693. /**
  75694. * Gets a list of the post processes contained in the effect.
  75695. * @param camera The camera to get the post processes on.
  75696. * @returns The list of the post processes in the effect.
  75697. */
  75698. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  75699. if (this._singleInstance) {
  75700. return this._postProcesses[0];
  75701. }
  75702. else {
  75703. if (!camera) {
  75704. return null;
  75705. }
  75706. return this._postProcesses[camera.name];
  75707. }
  75708. };
  75709. return PostProcessRenderEffect;
  75710. }());
  75711. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  75712. })(BABYLON || (BABYLON = {}));
  75713. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  75714. var BABYLON;
  75715. (function (BABYLON) {
  75716. var PostProcessRenderPipeline = /** @class */ (function () {
  75717. function PostProcessRenderPipeline(engine, name) {
  75718. this.engine = engine;
  75719. this._name = name;
  75720. this._renderEffects = {};
  75721. this._renderEffectsForIsolatedPass = new Array();
  75722. this._cameras = [];
  75723. }
  75724. PostProcessRenderPipeline.prototype.getClassName = function () {
  75725. return "PostProcessRenderPipeline";
  75726. };
  75727. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  75728. get: function () {
  75729. for (var renderEffectName in this._renderEffects) {
  75730. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75731. if (!this._renderEffects[renderEffectName].isSupported) {
  75732. return false;
  75733. }
  75734. }
  75735. }
  75736. return true;
  75737. },
  75738. enumerable: true,
  75739. configurable: true
  75740. });
  75741. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  75742. this._renderEffects[renderEffect._name] = renderEffect;
  75743. };
  75744. // private
  75745. /** @hidden */
  75746. PostProcessRenderPipeline.prototype._rebuild = function () {
  75747. };
  75748. /** @hidden */
  75749. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  75750. var renderEffects = this._renderEffects[renderEffectName];
  75751. if (!renderEffects) {
  75752. return;
  75753. }
  75754. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  75755. };
  75756. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  75757. var renderEffects = this._renderEffects[renderEffectName];
  75758. if (!renderEffects) {
  75759. return;
  75760. }
  75761. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  75762. };
  75763. /** @hidden */
  75764. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  75765. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75766. if (!cams) {
  75767. return;
  75768. }
  75769. var indicesToDelete = [];
  75770. var i;
  75771. for (i = 0; i < cams.length; i++) {
  75772. var camera = cams[i];
  75773. var cameraName = camera.name;
  75774. if (this._cameras.indexOf(camera) === -1) {
  75775. this._cameras[cameraName] = camera;
  75776. }
  75777. else if (unique) {
  75778. indicesToDelete.push(i);
  75779. }
  75780. }
  75781. for (i = 0; i < indicesToDelete.length; i++) {
  75782. cameras.splice(indicesToDelete[i], 1);
  75783. }
  75784. for (var renderEffectName in this._renderEffects) {
  75785. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75786. this._renderEffects[renderEffectName]._attachCameras(cams);
  75787. }
  75788. }
  75789. };
  75790. /** @hidden */
  75791. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  75792. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75793. if (!cams) {
  75794. return;
  75795. }
  75796. for (var renderEffectName in this._renderEffects) {
  75797. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75798. this._renderEffects[renderEffectName]._detachCameras(cams);
  75799. }
  75800. }
  75801. for (var i = 0; i < cams.length; i++) {
  75802. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  75803. }
  75804. };
  75805. /** @hidden */
  75806. PostProcessRenderPipeline.prototype._update = function () {
  75807. for (var renderEffectName in this._renderEffects) {
  75808. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  75809. this._renderEffects[renderEffectName]._update();
  75810. }
  75811. }
  75812. for (var i = 0; i < this._cameras.length; i++) {
  75813. var cameraName = this._cameras[i].name;
  75814. if (this._renderEffectsForIsolatedPass[cameraName]) {
  75815. this._renderEffectsForIsolatedPass[cameraName]._update();
  75816. }
  75817. }
  75818. };
  75819. /** @hidden */
  75820. PostProcessRenderPipeline.prototype._reset = function () {
  75821. this._renderEffects = {};
  75822. this._renderEffectsForIsolatedPass = new Array();
  75823. };
  75824. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  75825. // 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)
  75826. var effectKeys = Object.keys(this._renderEffects);
  75827. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  75828. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  75829. if (postProcesses) {
  75830. postProcesses[0].samples = sampleCount;
  75831. return true;
  75832. }
  75833. }
  75834. return false;
  75835. };
  75836. PostProcessRenderPipeline.prototype.dispose = function () {
  75837. // Must be implemented by children
  75838. };
  75839. __decorate([
  75840. BABYLON.serialize()
  75841. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  75842. return PostProcessRenderPipeline;
  75843. }());
  75844. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  75845. })(BABYLON || (BABYLON = {}));
  75846. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  75847. var BABYLON;
  75848. (function (BABYLON) {
  75849. /**
  75850. * This represents a depth renderer in Babylon.
  75851. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  75852. */
  75853. var DepthRenderer = /** @class */ (function () {
  75854. /**
  75855. * Instantiates a depth renderer
  75856. * @param scene The scene the renderer belongs to
  75857. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  75858. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  75859. */
  75860. function DepthRenderer(scene, type, camera) {
  75861. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  75862. if (camera === void 0) { camera = null; }
  75863. var _this = this;
  75864. this._scene = scene;
  75865. this._camera = camera;
  75866. var engine = scene.getEngine();
  75867. // Render target
  75868. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  75869. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75870. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75871. this._depthMap.refreshRate = 1;
  75872. this._depthMap.renderParticles = false;
  75873. this._depthMap.renderList = null;
  75874. // Camera to get depth map from to support multiple concurrent cameras
  75875. this._depthMap.activeCamera = this._camera;
  75876. this._depthMap.ignoreCameraViewport = true;
  75877. this._depthMap.useCameraPostProcesses = false;
  75878. // set default depth value to 1.0 (far away)
  75879. this._depthMap.onClearObservable.add(function (engine) {
  75880. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  75881. });
  75882. // Custom render function
  75883. var renderSubMesh = function (subMesh) {
  75884. var mesh = subMesh.getRenderingMesh();
  75885. var scene = _this._scene;
  75886. var engine = scene.getEngine();
  75887. var material = subMesh.getMaterial();
  75888. if (!material) {
  75889. return;
  75890. }
  75891. // Culling and reverse (right handed system)
  75892. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75893. // Managing instances
  75894. var batch = mesh._getInstancesRenderList(subMesh._id);
  75895. if (batch.mustReturn) {
  75896. return;
  75897. }
  75898. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75899. var camera = _this._camera || scene.activeCamera;
  75900. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  75901. engine.enableEffect(_this._effect);
  75902. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75903. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75904. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  75905. // Alpha test
  75906. if (material && material.needAlphaTesting()) {
  75907. var alphaTexture = material.getAlphaTestTexture();
  75908. if (alphaTexture) {
  75909. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75910. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75911. }
  75912. }
  75913. // Bones
  75914. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75915. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75916. }
  75917. // Draw
  75918. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75919. }
  75920. };
  75921. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75922. var index;
  75923. if (depthOnlySubMeshes.length) {
  75924. engine.setColorWrite(false);
  75925. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75926. renderSubMesh(depthOnlySubMeshes.data[index]);
  75927. }
  75928. engine.setColorWrite(true);
  75929. }
  75930. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75931. renderSubMesh(opaqueSubMeshes.data[index]);
  75932. }
  75933. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75934. renderSubMesh(alphaTestSubMeshes.data[index]);
  75935. }
  75936. };
  75937. }
  75938. /**
  75939. * Creates the depth rendering effect and checks if the effect is ready.
  75940. * @param subMesh The submesh to be used to render the depth map of
  75941. * @param useInstances If multiple world instances should be used
  75942. * @returns if the depth renderer is ready to render the depth map
  75943. */
  75944. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  75945. var material = subMesh.getMaterial();
  75946. if (material.disableDepthWrite) {
  75947. return false;
  75948. }
  75949. var defines = [];
  75950. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75951. var mesh = subMesh.getMesh();
  75952. // Alpha test
  75953. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  75954. defines.push("#define ALPHATEST");
  75955. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75956. attribs.push(BABYLON.VertexBuffer.UVKind);
  75957. defines.push("#define UV1");
  75958. }
  75959. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75960. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75961. defines.push("#define UV2");
  75962. }
  75963. }
  75964. // Bones
  75965. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75966. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75967. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75968. if (mesh.numBoneInfluencers > 4) {
  75969. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75970. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75971. }
  75972. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75973. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75974. }
  75975. else {
  75976. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75977. }
  75978. // Instances
  75979. if (useInstances) {
  75980. defines.push("#define INSTANCES");
  75981. attribs.push("world0");
  75982. attribs.push("world1");
  75983. attribs.push("world2");
  75984. attribs.push("world3");
  75985. }
  75986. // Get correct effect
  75987. var join = defines.join("\n");
  75988. if (this._cachedDefines !== join) {
  75989. this._cachedDefines = join;
  75990. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  75991. }
  75992. return this._effect.isReady();
  75993. };
  75994. /**
  75995. * Gets the texture which the depth map will be written to.
  75996. * @returns The depth map texture
  75997. */
  75998. DepthRenderer.prototype.getDepthMap = function () {
  75999. return this._depthMap;
  76000. };
  76001. /**
  76002. * Disposes of the depth renderer.
  76003. */
  76004. DepthRenderer.prototype.dispose = function () {
  76005. this._depthMap.dispose();
  76006. };
  76007. return DepthRenderer;
  76008. }());
  76009. BABYLON.DepthRenderer = DepthRenderer;
  76010. })(BABYLON || (BABYLON = {}));
  76011. //# sourceMappingURL=babylon.depthRenderer.js.map
  76012. var BABYLON;
  76013. (function (BABYLON) {
  76014. var SSAORenderingPipeline = /** @class */ (function (_super) {
  76015. __extends(SSAORenderingPipeline, _super);
  76016. /**
  76017. * @constructor
  76018. * @param {string} name - The rendering pipeline name
  76019. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76020. * @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 }
  76021. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76022. */
  76023. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  76024. var _this = _super.call(this, scene.getEngine(), name) || this;
  76025. // Members
  76026. /**
  76027. * The PassPostProcess id in the pipeline that contains the original scene color
  76028. */
  76029. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  76030. /**
  76031. * The SSAO PostProcess id in the pipeline
  76032. */
  76033. _this.SSAORenderEffect = "SSAORenderEffect";
  76034. /**
  76035. * The horizontal blur PostProcess id in the pipeline
  76036. */
  76037. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  76038. /**
  76039. * The vertical blur PostProcess id in the pipeline
  76040. */
  76041. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  76042. /**
  76043. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  76044. */
  76045. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  76046. /**
  76047. * The output strength of the SSAO post-process. Default value is 1.0.
  76048. */
  76049. _this.totalStrength = 1.0;
  76050. /**
  76051. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  76052. */
  76053. _this.radius = 0.0001;
  76054. /**
  76055. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  76056. * Must not be equal to fallOff and superior to fallOff.
  76057. * Default value is 0.975
  76058. */
  76059. _this.area = 0.0075;
  76060. /**
  76061. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  76062. * Must not be equal to area and inferior to area.
  76063. * Default value is 0.0
  76064. */
  76065. _this.fallOff = 0.000001;
  76066. /**
  76067. * The base color of the SSAO post-process
  76068. * The final result is "base + ssao" between [0, 1]
  76069. */
  76070. _this.base = 0.5;
  76071. _this._firstUpdate = true;
  76072. _this._scene = scene;
  76073. // Set up assets
  76074. _this._createRandomTexture();
  76075. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  76076. var ssaoRatio = ratio.ssaoRatio || ratio;
  76077. var combineRatio = ratio.combineRatio || ratio;
  76078. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  76079. _this._createSSAOPostProcess(ssaoRatio);
  76080. _this._createBlurPostProcess(ssaoRatio);
  76081. _this._createSSAOCombinePostProcess(combineRatio);
  76082. // Set up pipeline
  76083. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  76084. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  76085. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  76086. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  76087. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  76088. // Finish
  76089. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76090. if (cameras)
  76091. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76092. return _this;
  76093. }
  76094. // Public Methods
  76095. /**
  76096. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  76097. */
  76098. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  76099. if (disableDepthRender === void 0) { disableDepthRender = false; }
  76100. for (var i = 0; i < this._scene.cameras.length; i++) {
  76101. var camera = this._scene.cameras[i];
  76102. this._originalColorPostProcess.dispose(camera);
  76103. this._ssaoPostProcess.dispose(camera);
  76104. this._blurHPostProcess.dispose(camera);
  76105. this._blurVPostProcess.dispose(camera);
  76106. this._ssaoCombinePostProcess.dispose(camera);
  76107. }
  76108. this._randomTexture.dispose();
  76109. if (disableDepthRender)
  76110. this._scene.disableDepthRenderer();
  76111. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  76112. _super.prototype.dispose.call(this);
  76113. };
  76114. // Private Methods
  76115. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  76116. var _this = this;
  76117. var size = 16;
  76118. 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);
  76119. 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);
  76120. this._blurHPostProcess.onActivateObservable.add(function () {
  76121. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  76122. _this._blurHPostProcess.kernel = size * dw;
  76123. });
  76124. this._blurVPostProcess.onActivateObservable.add(function () {
  76125. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  76126. _this._blurVPostProcess.kernel = size * dw;
  76127. });
  76128. };
  76129. /** @hidden */
  76130. SSAORenderingPipeline.prototype._rebuild = function () {
  76131. this._firstUpdate = true;
  76132. _super.prototype._rebuild.call(this);
  76133. };
  76134. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  76135. var _this = this;
  76136. var numSamples = 16;
  76137. var sampleSphere = [
  76138. 0.5381, 0.1856, -0.4319,
  76139. 0.1379, 0.2486, 0.4430,
  76140. 0.3371, 0.5679, -0.0057,
  76141. -0.6999, -0.0451, -0.0019,
  76142. 0.0689, -0.1598, -0.8547,
  76143. 0.0560, 0.0069, -0.1843,
  76144. -0.0146, 0.1402, 0.0762,
  76145. 0.0100, -0.1924, -0.0344,
  76146. -0.3577, -0.5301, -0.4358,
  76147. -0.3169, 0.1063, 0.0158,
  76148. 0.0103, -0.5869, 0.0046,
  76149. -0.0897, -0.4940, 0.3287,
  76150. 0.7119, -0.0154, -0.0918,
  76151. -0.0533, 0.0596, -0.5411,
  76152. 0.0352, -0.0631, 0.5460,
  76153. -0.4776, 0.2847, -0.0271
  76154. ];
  76155. var samplesFactor = 1.0 / numSamples;
  76156. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  76157. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  76158. "area", "fallOff", "base", "range", "viewport"
  76159. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  76160. this._ssaoPostProcess.onApply = function (effect) {
  76161. if (_this._firstUpdate) {
  76162. effect.setArray3("sampleSphere", sampleSphere);
  76163. effect.setFloat("samplesFactor", samplesFactor);
  76164. effect.setFloat("randTextureTiles", 4.0);
  76165. }
  76166. effect.setFloat("totalStrength", _this.totalStrength);
  76167. effect.setFloat("radius", _this.radius);
  76168. effect.setFloat("area", _this.area);
  76169. effect.setFloat("fallOff", _this.fallOff);
  76170. effect.setFloat("base", _this.base);
  76171. effect.setTexture("textureSampler", _this._depthTexture);
  76172. effect.setTexture("randomSampler", _this._randomTexture);
  76173. };
  76174. };
  76175. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  76176. var _this = this;
  76177. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76178. this._ssaoCombinePostProcess.onApply = function (effect) {
  76179. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  76180. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  76181. };
  76182. };
  76183. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  76184. var size = 512;
  76185. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76186. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76187. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76188. var context = this._randomTexture.getContext();
  76189. var rand = function (min, max) {
  76190. return Math.random() * (max - min) + min;
  76191. };
  76192. var randVector = BABYLON.Vector3.Zero();
  76193. for (var x = 0; x < size; x++) {
  76194. for (var y = 0; y < size; y++) {
  76195. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  76196. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  76197. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  76198. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  76199. context.fillRect(x, y, 1, 1);
  76200. }
  76201. }
  76202. this._randomTexture.update(false);
  76203. };
  76204. __decorate([
  76205. BABYLON.serialize()
  76206. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  76207. __decorate([
  76208. BABYLON.serialize()
  76209. ], SSAORenderingPipeline.prototype, "radius", void 0);
  76210. __decorate([
  76211. BABYLON.serialize()
  76212. ], SSAORenderingPipeline.prototype, "area", void 0);
  76213. __decorate([
  76214. BABYLON.serialize()
  76215. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  76216. __decorate([
  76217. BABYLON.serialize()
  76218. ], SSAORenderingPipeline.prototype, "base", void 0);
  76219. return SSAORenderingPipeline;
  76220. }(BABYLON.PostProcessRenderPipeline));
  76221. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  76222. })(BABYLON || (BABYLON = {}));
  76223. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  76224. var BABYLON;
  76225. (function (BABYLON) {
  76226. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  76227. __extends(SSAO2RenderingPipeline, _super);
  76228. /**
  76229. * @constructor
  76230. * @param {string} name - The rendering pipeline name
  76231. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76232. * @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 }
  76233. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76234. */
  76235. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  76236. var _this = _super.call(this, scene.getEngine(), name) || this;
  76237. // Members
  76238. /**
  76239. * The PassPostProcess id in the pipeline that contains the original scene color
  76240. */
  76241. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  76242. /**
  76243. * The SSAO PostProcess id in the pipeline
  76244. */
  76245. _this.SSAORenderEffect = "SSAORenderEffect";
  76246. /**
  76247. * The horizontal blur PostProcess id in the pipeline
  76248. */
  76249. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  76250. /**
  76251. * The vertical blur PostProcess id in the pipeline
  76252. */
  76253. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  76254. /**
  76255. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  76256. */
  76257. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  76258. /**
  76259. * The output strength of the SSAO post-process. Default value is 1.0.
  76260. */
  76261. _this.totalStrength = 1.0;
  76262. /**
  76263. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  76264. */
  76265. _this.maxZ = 100.0;
  76266. /**
  76267. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  76268. */
  76269. _this.minZAspect = 0.2;
  76270. /**
  76271. * Number of samples used for the SSAO calculations. Default value is 8
  76272. */
  76273. _this._samples = 8;
  76274. /**
  76275. * Are we using bilateral blur ?
  76276. */
  76277. _this._expensiveBlur = true;
  76278. /**
  76279. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  76280. */
  76281. _this.radius = 2.0;
  76282. /**
  76283. * The base color of the SSAO post-process
  76284. * The final result is "base + ssao" between [0, 1]
  76285. */
  76286. _this.base = 0.1;
  76287. _this._firstUpdate = true;
  76288. _this._scene = scene;
  76289. _this._ratio = ratio;
  76290. if (!_this.isSupported) {
  76291. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  76292. return _this;
  76293. }
  76294. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  76295. var blurRatio = _this._ratio.blurRatio || ratio;
  76296. // Set up assets
  76297. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  76298. _this._createRandomTexture();
  76299. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  76300. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  76301. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  76302. _this._createSSAOPostProcess(1.0);
  76303. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  76304. _this._createSSAOCombinePostProcess(blurRatio);
  76305. // Set up pipeline
  76306. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  76307. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  76308. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  76309. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  76310. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  76311. // Finish
  76312. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76313. if (cameras)
  76314. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76315. return _this;
  76316. }
  76317. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  76318. get: function () {
  76319. return this._samples;
  76320. },
  76321. set: function (n) {
  76322. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  76323. this._samples = n;
  76324. this._sampleSphere = this._generateHemisphere();
  76325. this._firstUpdate = true;
  76326. },
  76327. enumerable: true,
  76328. configurable: true
  76329. });
  76330. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  76331. get: function () {
  76332. return this._expensiveBlur;
  76333. },
  76334. set: function (b) {
  76335. 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"]);
  76336. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  76337. this._expensiveBlur = b;
  76338. this._firstUpdate = true;
  76339. },
  76340. enumerable: true,
  76341. configurable: true
  76342. });
  76343. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  76344. /**
  76345. * Support test.
  76346. */
  76347. get: function () {
  76348. var engine = BABYLON.Engine.LastCreatedEngine;
  76349. if (!engine) {
  76350. return false;
  76351. }
  76352. return engine.getCaps().drawBuffersExtension;
  76353. },
  76354. enumerable: true,
  76355. configurable: true
  76356. });
  76357. // Public Methods
  76358. /**
  76359. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  76360. */
  76361. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  76362. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  76363. for (var i = 0; i < this._scene.cameras.length; i++) {
  76364. var camera = this._scene.cameras[i];
  76365. this._originalColorPostProcess.dispose(camera);
  76366. this._ssaoPostProcess.dispose(camera);
  76367. this._blurHPostProcess.dispose(camera);
  76368. this._blurVPostProcess.dispose(camera);
  76369. this._ssaoCombinePostProcess.dispose(camera);
  76370. }
  76371. this._randomTexture.dispose();
  76372. if (disableGeometryBufferRenderer)
  76373. this._scene.disableGeometryBufferRenderer();
  76374. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  76375. _super.prototype.dispose.call(this);
  76376. };
  76377. // Private Methods
  76378. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  76379. var _this = this;
  76380. this._samplerOffsets = [];
  76381. var expensive = this.expensiveBlur;
  76382. for (var i = -8; i < 8; i++) {
  76383. this._samplerOffsets.push(i * 2 + 0.5);
  76384. }
  76385. 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");
  76386. this._blurHPostProcess.onApply = function (effect) {
  76387. if (!_this._scene.activeCamera) {
  76388. return;
  76389. }
  76390. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  76391. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76392. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76393. effect.setFloat("radius", _this.radius);
  76394. effect.setTexture("depthSampler", _this._depthTexture);
  76395. if (_this._firstUpdate) {
  76396. effect.setArray("samplerOffsets", _this._samplerOffsets);
  76397. }
  76398. };
  76399. 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");
  76400. this._blurVPostProcess.onApply = function (effect) {
  76401. if (!_this._scene.activeCamera) {
  76402. return;
  76403. }
  76404. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  76405. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76406. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76407. effect.setFloat("radius", _this.radius);
  76408. effect.setTexture("depthSampler", _this._depthTexture);
  76409. if (_this._firstUpdate) {
  76410. effect.setArray("samplerOffsets", _this._samplerOffsets);
  76411. _this._firstUpdate = false;
  76412. }
  76413. };
  76414. };
  76415. /** @hidden */
  76416. SSAO2RenderingPipeline.prototype._rebuild = function () {
  76417. this._firstUpdate = true;
  76418. _super.prototype._rebuild.call(this);
  76419. };
  76420. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  76421. var numSamples = this.samples;
  76422. var result = [];
  76423. var vector, scale;
  76424. var rand = function (min, max) {
  76425. return Math.random() * (max - min) + min;
  76426. };
  76427. var i = 0;
  76428. while (i < numSamples) {
  76429. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  76430. vector.normalize();
  76431. scale = i / numSamples;
  76432. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  76433. vector.scaleInPlace(scale);
  76434. result.push(vector.x, vector.y, vector.z);
  76435. i++;
  76436. }
  76437. return result;
  76438. };
  76439. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  76440. var _this = this;
  76441. var numSamples = this.samples;
  76442. this._sampleSphere = this._generateHemisphere();
  76443. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  76444. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  76445. "base", "range", "projection", "near", "far", "texelSize",
  76446. "xViewport", "yViewport", "maxZ", "minZAspect"
  76447. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  76448. this._ssaoPostProcess.onApply = function (effect) {
  76449. if (_this._firstUpdate) {
  76450. effect.setArray3("sampleSphere", _this._sampleSphere);
  76451. effect.setFloat("randTextureTiles", 4.0);
  76452. }
  76453. if (!_this._scene.activeCamera) {
  76454. return;
  76455. }
  76456. effect.setFloat("samplesFactor", 1 / _this.samples);
  76457. effect.setFloat("totalStrength", _this.totalStrength);
  76458. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  76459. effect.setFloat("radius", _this.radius);
  76460. effect.setFloat("maxZ", _this.maxZ);
  76461. effect.setFloat("minZAspect", _this.minZAspect);
  76462. effect.setFloat("base", _this.base);
  76463. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76464. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76465. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  76466. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  76467. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  76468. effect.setTexture("textureSampler", _this._depthTexture);
  76469. effect.setTexture("normalSampler", _this._normalTexture);
  76470. effect.setTexture("randomSampler", _this._randomTexture);
  76471. };
  76472. };
  76473. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  76474. var _this = this;
  76475. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76476. this._ssaoCombinePostProcess.onApply = function (effect) {
  76477. var viewport = _this._scene.activeCamera.viewport;
  76478. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  76479. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  76480. };
  76481. };
  76482. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  76483. var size = 512;
  76484. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76485. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76486. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76487. var context = this._randomTexture.getContext();
  76488. var rand = function (min, max) {
  76489. return Math.random() * (max - min) + min;
  76490. };
  76491. var randVector = BABYLON.Vector3.Zero();
  76492. for (var x = 0; x < size; x++) {
  76493. for (var y = 0; y < size; y++) {
  76494. randVector.x = rand(0.0, 1.0);
  76495. randVector.y = rand(0.0, 1.0);
  76496. randVector.z = 0.0;
  76497. randVector.normalize();
  76498. randVector.scaleInPlace(255);
  76499. randVector.x = Math.floor(randVector.x);
  76500. randVector.y = Math.floor(randVector.y);
  76501. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  76502. context.fillRect(x, y, 1, 1);
  76503. }
  76504. }
  76505. this._randomTexture.update(false);
  76506. };
  76507. /**
  76508. * Serialize the rendering pipeline (Used when exporting)
  76509. * @returns the serialized object
  76510. */
  76511. SSAO2RenderingPipeline.prototype.serialize = function () {
  76512. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76513. serializationObject.customType = "SSAO2RenderingPipeline";
  76514. return serializationObject;
  76515. };
  76516. /**
  76517. * Parse the serialized pipeline
  76518. * @param source Source pipeline.
  76519. * @param scene The scene to load the pipeline to.
  76520. * @param rootUrl The URL of the serialized pipeline.
  76521. * @returns An instantiated pipeline from the serialized object.
  76522. */
  76523. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  76524. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76525. };
  76526. __decorate([
  76527. BABYLON.serialize()
  76528. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  76529. __decorate([
  76530. BABYLON.serialize()
  76531. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  76532. __decorate([
  76533. BABYLON.serialize()
  76534. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  76535. __decorate([
  76536. BABYLON.serialize("samples")
  76537. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  76538. __decorate([
  76539. BABYLON.serialize()
  76540. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  76541. __decorate([
  76542. BABYLON.serialize("expensiveBlur")
  76543. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  76544. __decorate([
  76545. BABYLON.serialize()
  76546. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  76547. __decorate([
  76548. BABYLON.serialize()
  76549. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  76550. return SSAO2RenderingPipeline;
  76551. }(BABYLON.PostProcessRenderPipeline));
  76552. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  76553. })(BABYLON || (BABYLON = {}));
  76554. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  76555. // BABYLON.JS Chromatic Aberration GLSL Shader
  76556. // Author: Olivier Guyot
  76557. // Separates very slightly R, G and B colors on the edges of the screen
  76558. // Inspired by Francois Tarlier & Martins Upitis
  76559. var BABYLON;
  76560. (function (BABYLON) {
  76561. var LensRenderingPipeline = /** @class */ (function (_super) {
  76562. __extends(LensRenderingPipeline, _super);
  76563. /**
  76564. * @constructor
  76565. *
  76566. * Effect parameters are as follow:
  76567. * {
  76568. * chromatic_aberration: number; // from 0 to x (1 for realism)
  76569. * edge_blur: number; // from 0 to x (1 for realism)
  76570. * distortion: number; // from 0 to x (1 for realism)
  76571. * grain_amount: number; // from 0 to 1
  76572. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  76573. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  76574. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  76575. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  76576. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  76577. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  76578. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  76579. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  76580. * }
  76581. * Note: if an effect parameter is unset, effect is disabled
  76582. *
  76583. * @param {string} name - The rendering pipeline name
  76584. * @param {object} parameters - An object containing all parameters (see above)
  76585. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76586. * @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)
  76587. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76588. */
  76589. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  76590. if (ratio === void 0) { ratio = 1.0; }
  76591. var _this = _super.call(this, scene.getEngine(), name) || this;
  76592. // Lens effects can be of the following:
  76593. // - chromatic aberration (slight shift of RGB colors)
  76594. // - blur on the edge of the lens
  76595. // - lens distortion
  76596. // - depth-of-field blur & highlights enhancing
  76597. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  76598. // - grain effect (noise or custom texture)
  76599. // Two additional texture samplers are needed:
  76600. // - depth map (for depth-of-field)
  76601. // - grain texture
  76602. /**
  76603. * The chromatic aberration PostProcess id in the pipeline
  76604. */
  76605. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  76606. /**
  76607. * The highlights enhancing PostProcess id in the pipeline
  76608. */
  76609. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  76610. /**
  76611. * The depth-of-field PostProcess id in the pipeline
  76612. */
  76613. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  76614. _this._scene = scene;
  76615. // Fetch texture samplers
  76616. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  76617. if (parameters.grain_texture) {
  76618. _this._grainTexture = parameters.grain_texture;
  76619. }
  76620. else {
  76621. _this._createGrainTexture();
  76622. }
  76623. // save parameters
  76624. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  76625. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  76626. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  76627. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  76628. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  76629. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  76630. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  76631. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  76632. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  76633. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  76634. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  76635. // Create effects
  76636. _this._createChromaticAberrationPostProcess(ratio);
  76637. _this._createHighlightsPostProcess(ratio);
  76638. _this._createDepthOfFieldPostProcess(ratio / 4);
  76639. // Set up pipeline
  76640. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  76641. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  76642. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  76643. if (_this._highlightsGain === -1) {
  76644. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  76645. }
  76646. // Finish
  76647. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76648. if (cameras) {
  76649. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76650. }
  76651. return _this;
  76652. }
  76653. // public methods (self explanatory)
  76654. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  76655. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  76656. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  76657. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  76658. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  76659. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  76660. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  76661. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  76662. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  76663. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  76664. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  76665. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  76666. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  76667. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  76668. };
  76669. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  76670. this._highlightsPostProcess.updateEffect();
  76671. };
  76672. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  76673. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  76674. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  76675. this._highlightsGain = amount;
  76676. };
  76677. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  76678. if (this._highlightsGain === -1) {
  76679. this._highlightsGain = 1.0;
  76680. }
  76681. this._highlightsThreshold = amount;
  76682. };
  76683. LensRenderingPipeline.prototype.disableHighlights = function () {
  76684. this._highlightsGain = -1;
  76685. };
  76686. /**
  76687. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  76688. */
  76689. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  76690. if (disableDepthRender === void 0) { disableDepthRender = false; }
  76691. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  76692. this._chromaticAberrationPostProcess = null;
  76693. this._highlightsPostProcess = null;
  76694. this._depthOfFieldPostProcess = null;
  76695. this._grainTexture.dispose();
  76696. if (disableDepthRender)
  76697. this._scene.disableDepthRenderer();
  76698. };
  76699. // colors shifting and distortion
  76700. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  76701. var _this = this;
  76702. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  76703. [], // samplers
  76704. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76705. this._chromaticAberrationPostProcess.onApply = function (effect) {
  76706. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  76707. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76708. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76709. effect.setFloat('radialIntensity', 1);
  76710. effect.setFloat2('direction', 17, 17);
  76711. effect.setFloat2('centerPosition', 0.5, 0.5);
  76712. };
  76713. };
  76714. // highlights enhancing
  76715. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  76716. var _this = this;
  76717. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  76718. [], // samplers
  76719. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  76720. this._highlightsPostProcess.onApply = function (effect) {
  76721. effect.setFloat('gain', _this._highlightsGain);
  76722. effect.setFloat('threshold', _this._highlightsThreshold);
  76723. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  76724. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76725. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76726. };
  76727. };
  76728. // colors shifting and distortion
  76729. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  76730. var _this = this;
  76731. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  76732. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  76733. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  76734. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76735. this._depthOfFieldPostProcess.onApply = function (effect) {
  76736. effect.setTexture("depthSampler", _this._depthTexture);
  76737. effect.setTexture("grainSampler", _this._grainTexture);
  76738. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  76739. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  76740. effect.setFloat('grain_amount', _this._grainAmount);
  76741. effect.setBool('blur_noise', _this._blurNoise);
  76742. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  76743. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  76744. effect.setFloat('distortion', _this._distortion);
  76745. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  76746. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  76747. effect.setFloat('aperture', _this._dofAperture);
  76748. effect.setFloat('darken', _this._dofDarken);
  76749. effect.setFloat('edge_blur', _this._edgeBlur);
  76750. effect.setBool('highlights', (_this._highlightsGain !== -1));
  76751. if (_this._scene.activeCamera) {
  76752. effect.setFloat('near', _this._scene.activeCamera.minZ);
  76753. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  76754. }
  76755. };
  76756. };
  76757. // creates a black and white random noise texture, 512x512
  76758. LensRenderingPipeline.prototype._createGrainTexture = function () {
  76759. var size = 512;
  76760. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76761. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76762. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76763. var context = this._grainTexture.getContext();
  76764. var rand = function (min, max) {
  76765. return Math.random() * (max - min) + min;
  76766. };
  76767. var value;
  76768. for (var x = 0; x < size; x++) {
  76769. for (var y = 0; y < size; y++) {
  76770. value = Math.floor(rand(0.42, 0.58) * 255);
  76771. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  76772. context.fillRect(x, y, 1, 1);
  76773. }
  76774. }
  76775. this._grainTexture.update(false);
  76776. };
  76777. return LensRenderingPipeline;
  76778. }(BABYLON.PostProcessRenderPipeline));
  76779. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  76780. })(BABYLON || (BABYLON = {}));
  76781. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  76782. var BABYLON;
  76783. (function (BABYLON) {
  76784. var StandardRenderingPipeline = /** @class */ (function (_super) {
  76785. __extends(StandardRenderingPipeline, _super);
  76786. /**
  76787. * @constructor
  76788. * @param {string} name - The rendering pipeline name
  76789. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76790. * @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)
  76791. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  76792. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76793. */
  76794. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  76795. if (originalPostProcess === void 0) { originalPostProcess = null; }
  76796. var _this = _super.call(this, scene.getEngine(), name) || this;
  76797. _this.downSampleX4PostProcess = null;
  76798. _this.brightPassPostProcess = null;
  76799. _this.blurHPostProcesses = [];
  76800. _this.blurVPostProcesses = [];
  76801. _this.textureAdderPostProcess = null;
  76802. _this.volumetricLightPostProcess = null;
  76803. _this.volumetricLightSmoothXPostProcess = null;
  76804. _this.volumetricLightSmoothYPostProcess = null;
  76805. _this.volumetricLightMergePostProces = null;
  76806. _this.volumetricLightFinalPostProcess = null;
  76807. _this.luminancePostProcess = null;
  76808. _this.luminanceDownSamplePostProcesses = [];
  76809. _this.hdrPostProcess = null;
  76810. _this.textureAdderFinalPostProcess = null;
  76811. _this.lensFlareFinalPostProcess = null;
  76812. _this.hdrFinalPostProcess = null;
  76813. _this.lensFlarePostProcess = null;
  76814. _this.lensFlareComposePostProcess = null;
  76815. _this.motionBlurPostProcess = null;
  76816. _this.depthOfFieldPostProcess = null;
  76817. // Values
  76818. _this.brightThreshold = 1.0;
  76819. _this.blurWidth = 512.0;
  76820. _this.horizontalBlur = false;
  76821. _this.exposure = 1.0;
  76822. _this.lensTexture = null;
  76823. _this.volumetricLightCoefficient = 0.2;
  76824. _this.volumetricLightPower = 4.0;
  76825. _this.volumetricLightBlurScale = 64.0;
  76826. _this.sourceLight = null;
  76827. _this.hdrMinimumLuminance = 1.0;
  76828. _this.hdrDecreaseRate = 0.5;
  76829. _this.hdrIncreaseRate = 0.5;
  76830. _this.lensColorTexture = null;
  76831. _this.lensFlareStrength = 20.0;
  76832. _this.lensFlareGhostDispersal = 1.4;
  76833. _this.lensFlareHaloWidth = 0.7;
  76834. _this.lensFlareDistortionStrength = 16.0;
  76835. _this.lensStarTexture = null;
  76836. _this.lensFlareDirtTexture = null;
  76837. _this.depthOfFieldDistance = 10.0;
  76838. _this.depthOfFieldBlurWidth = 64.0;
  76839. _this.motionStrength = 1.0;
  76840. // IAnimatable
  76841. _this.animations = [];
  76842. _this._currentDepthOfFieldSource = null;
  76843. _this._hdrCurrentLuminance = 1.0;
  76844. // Getters and setters
  76845. _this._bloomEnabled = true;
  76846. _this._depthOfFieldEnabled = false;
  76847. _this._vlsEnabled = false;
  76848. _this._lensFlareEnabled = false;
  76849. _this._hdrEnabled = false;
  76850. _this._motionBlurEnabled = false;
  76851. _this._motionBlurSamples = 64.0;
  76852. _this._volumetricLightStepsCount = 50.0;
  76853. _this._cameras = cameras || [];
  76854. // Initialize
  76855. _this._scene = scene;
  76856. _this._basePostProcess = originalPostProcess;
  76857. _this._ratio = ratio;
  76858. // Misc
  76859. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76860. // Finish
  76861. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76862. _this._buildPipeline();
  76863. return _this;
  76864. }
  76865. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  76866. get: function () {
  76867. return this._bloomEnabled;
  76868. },
  76869. set: function (enabled) {
  76870. if (this._bloomEnabled === enabled) {
  76871. return;
  76872. }
  76873. this._bloomEnabled = enabled;
  76874. this._buildPipeline();
  76875. },
  76876. enumerable: true,
  76877. configurable: true
  76878. });
  76879. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  76880. get: function () {
  76881. return this._depthOfFieldEnabled;
  76882. },
  76883. set: function (enabled) {
  76884. if (this._depthOfFieldEnabled === enabled) {
  76885. return;
  76886. }
  76887. this._depthOfFieldEnabled = enabled;
  76888. this._buildPipeline();
  76889. },
  76890. enumerable: true,
  76891. configurable: true
  76892. });
  76893. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  76894. get: function () {
  76895. return this._lensFlareEnabled;
  76896. },
  76897. set: function (enabled) {
  76898. if (this._lensFlareEnabled === enabled) {
  76899. return;
  76900. }
  76901. this._lensFlareEnabled = enabled;
  76902. this._buildPipeline();
  76903. },
  76904. enumerable: true,
  76905. configurable: true
  76906. });
  76907. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  76908. get: function () {
  76909. return this._hdrEnabled;
  76910. },
  76911. set: function (enabled) {
  76912. if (this._hdrEnabled === enabled) {
  76913. return;
  76914. }
  76915. this._hdrEnabled = enabled;
  76916. this._buildPipeline();
  76917. },
  76918. enumerable: true,
  76919. configurable: true
  76920. });
  76921. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  76922. get: function () {
  76923. return this._vlsEnabled;
  76924. },
  76925. set: function (enabled) {
  76926. if (this._vlsEnabled === enabled) {
  76927. return;
  76928. }
  76929. if (enabled) {
  76930. var geometry = this._scene.enableGeometryBufferRenderer();
  76931. if (!geometry) {
  76932. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  76933. return;
  76934. }
  76935. }
  76936. this._vlsEnabled = enabled;
  76937. this._buildPipeline();
  76938. },
  76939. enumerable: true,
  76940. configurable: true
  76941. });
  76942. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  76943. get: function () {
  76944. return this._motionBlurEnabled;
  76945. },
  76946. set: function (enabled) {
  76947. if (this._motionBlurEnabled === enabled) {
  76948. return;
  76949. }
  76950. this._motionBlurEnabled = enabled;
  76951. this._buildPipeline();
  76952. },
  76953. enumerable: true,
  76954. configurable: true
  76955. });
  76956. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  76957. get: function () {
  76958. return this._volumetricLightStepsCount;
  76959. },
  76960. set: function (count) {
  76961. if (this.volumetricLightPostProcess) {
  76962. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  76963. }
  76964. this._volumetricLightStepsCount = count;
  76965. },
  76966. enumerable: true,
  76967. configurable: true
  76968. });
  76969. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  76970. get: function () {
  76971. return this._motionBlurSamples;
  76972. },
  76973. set: function (samples) {
  76974. if (this.motionBlurPostProcess) {
  76975. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  76976. }
  76977. this._motionBlurSamples = samples;
  76978. },
  76979. enumerable: true,
  76980. configurable: true
  76981. });
  76982. StandardRenderingPipeline.prototype._buildPipeline = function () {
  76983. var _this = this;
  76984. var ratio = this._ratio;
  76985. var scene = this._scene;
  76986. this._disposePostProcesses();
  76987. this._reset();
  76988. // Create pass post-process
  76989. if (!this._basePostProcess) {
  76990. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  76991. this.originalPostProcess.onApply = function (effect) {
  76992. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  76993. };
  76994. }
  76995. else {
  76996. this.originalPostProcess = this._basePostProcess;
  76997. }
  76998. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  76999. this._currentDepthOfFieldSource = this.originalPostProcess;
  77000. if (this._bloomEnabled) {
  77001. // Create down sample X4 post-process
  77002. this._createDownSampleX4PostProcess(scene, ratio / 2);
  77003. // Create bright pass post-process
  77004. this._createBrightPassPostProcess(scene, ratio / 2);
  77005. // Create gaussian blur post-processes (down sampling blurs)
  77006. this._createBlurPostProcesses(scene, ratio / 4, 1);
  77007. // Create texture adder post-process
  77008. this._createTextureAdderPostProcess(scene, ratio);
  77009. // Create depth-of-field source post-process
  77010. 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);
  77011. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  77012. }
  77013. if (this._vlsEnabled) {
  77014. // Create volumetric light
  77015. this._createVolumetricLightPostProcess(scene, ratio);
  77016. // Create volumetric light final post-process
  77017. 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);
  77018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  77019. }
  77020. if (this._lensFlareEnabled) {
  77021. // Create lens flare post-process
  77022. this._createLensFlarePostProcess(scene, ratio);
  77023. // Create depth-of-field source post-process post lens-flare and disable it now
  77024. 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);
  77025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  77026. }
  77027. if (this._hdrEnabled) {
  77028. // Create luminance
  77029. this._createLuminancePostProcesses(scene, this._floatTextureType);
  77030. // Create HDR
  77031. this._createHdrPostProcess(scene, ratio);
  77032. // Create depth-of-field source post-process post hdr and disable it now
  77033. 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);
  77034. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  77035. }
  77036. if (this._depthOfFieldEnabled) {
  77037. // Create gaussian blur used by depth-of-field
  77038. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  77039. // Create depth-of-field post-process
  77040. this._createDepthOfFieldPostProcess(scene, ratio);
  77041. }
  77042. if (this._motionBlurEnabled) {
  77043. // Create motion blur post-process
  77044. this._createMotionBlurPostProcess(scene, ratio);
  77045. }
  77046. if (this._cameras !== null) {
  77047. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  77048. }
  77049. };
  77050. // Down Sample X4 Post-Processs
  77051. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  77052. var _this = this;
  77053. var downSampleX4Offsets = new Array(32);
  77054. 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);
  77055. this.downSampleX4PostProcess.onApply = function (effect) {
  77056. var id = 0;
  77057. var width = _this.downSampleX4PostProcess.width;
  77058. var height = _this.downSampleX4PostProcess.height;
  77059. for (var i = -2; i < 2; i++) {
  77060. for (var j = -2; j < 2; j++) {
  77061. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  77062. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  77063. id += 2;
  77064. }
  77065. }
  77066. effect.setArray2("dsOffsets", downSampleX4Offsets);
  77067. };
  77068. // Add to pipeline
  77069. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  77070. };
  77071. // Brightpass Post-Process
  77072. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  77073. var _this = this;
  77074. var brightOffsets = new Array(8);
  77075. 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);
  77076. this.brightPassPostProcess.onApply = function (effect) {
  77077. var sU = (1.0 / _this.brightPassPostProcess.width);
  77078. var sV = (1.0 / _this.brightPassPostProcess.height);
  77079. brightOffsets[0] = -0.5 * sU;
  77080. brightOffsets[1] = 0.5 * sV;
  77081. brightOffsets[2] = 0.5 * sU;
  77082. brightOffsets[3] = 0.5 * sV;
  77083. brightOffsets[4] = -0.5 * sU;
  77084. brightOffsets[5] = -0.5 * sV;
  77085. brightOffsets[6] = 0.5 * sU;
  77086. brightOffsets[7] = -0.5 * sV;
  77087. effect.setArray2("dsOffsets", brightOffsets);
  77088. effect.setFloat("brightThreshold", _this.brightThreshold);
  77089. };
  77090. // Add to pipeline
  77091. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  77092. };
  77093. // Create blur H&V post-processes
  77094. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  77095. var _this = this;
  77096. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  77097. var engine = scene.getEngine();
  77098. 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);
  77099. 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);
  77100. blurX.onActivateObservable.add(function () {
  77101. var dw = blurX.width / engine.getRenderWidth();
  77102. blurX.kernel = _this[blurWidthKey] * dw;
  77103. });
  77104. blurY.onActivateObservable.add(function () {
  77105. var dw = blurY.height / engine.getRenderHeight();
  77106. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  77107. });
  77108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  77109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  77110. this.blurHPostProcesses.push(blurX);
  77111. this.blurVPostProcesses.push(blurY);
  77112. };
  77113. // Create texture adder post-process
  77114. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  77115. var _this = this;
  77116. 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);
  77117. this.textureAdderPostProcess.onApply = function (effect) {
  77118. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  77119. effect.setTexture("lensSampler", _this.lensTexture);
  77120. effect.setFloat("exposure", _this.exposure);
  77121. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  77122. };
  77123. // Add to pipeline
  77124. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  77125. };
  77126. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  77127. var _this = this;
  77128. var geometryRenderer = scene.enableGeometryBufferRenderer();
  77129. geometryRenderer.enablePosition = true;
  77130. var geometry = geometryRenderer.getGBuffer();
  77131. // Base post-process
  77132. 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));
  77133. var depthValues = BABYLON.Vector2.Zero();
  77134. this.volumetricLightPostProcess.onApply = function (effect) {
  77135. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  77136. var generator = _this.sourceLight.getShadowGenerator();
  77137. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  77138. effect.setTexture("positionSampler", geometry.textures[2]);
  77139. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  77140. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  77141. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  77142. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  77143. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  77144. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  77145. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  77146. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  77147. effect.setVector2("depthValues", depthValues);
  77148. }
  77149. };
  77150. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  77151. // Smooth
  77152. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  77153. // Merge
  77154. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  77155. this.volumetricLightMergePostProces.onApply = function (effect) {
  77156. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  77157. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  77158. };
  77159. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  77160. };
  77161. // Create luminance
  77162. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  77163. var _this = this;
  77164. // Create luminance
  77165. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  77166. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  77167. var offsets = [];
  77168. this.luminancePostProcess.onApply = function (effect) {
  77169. var sU = (1.0 / _this.luminancePostProcess.width);
  77170. var sV = (1.0 / _this.luminancePostProcess.height);
  77171. offsets[0] = -0.5 * sU;
  77172. offsets[1] = 0.5 * sV;
  77173. offsets[2] = 0.5 * sU;
  77174. offsets[3] = 0.5 * sV;
  77175. offsets[4] = -0.5 * sU;
  77176. offsets[5] = -0.5 * sV;
  77177. offsets[6] = 0.5 * sU;
  77178. offsets[7] = -0.5 * sV;
  77179. effect.setArray2("lumOffsets", offsets);
  77180. };
  77181. // Add to pipeline
  77182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  77183. // Create down sample luminance
  77184. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  77185. var size = Math.pow(3, i);
  77186. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  77187. if (i === 0) {
  77188. defines += "#define FINAL_DOWN_SAMPLER";
  77189. }
  77190. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  77191. this.luminanceDownSamplePostProcesses.push(postProcess);
  77192. }
  77193. // Create callbacks and add effects
  77194. var lastLuminance = this.luminancePostProcess;
  77195. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  77196. var downSampleOffsets = new Array(18);
  77197. pp.onApply = function (effect) {
  77198. if (!lastLuminance) {
  77199. return;
  77200. }
  77201. var id = 0;
  77202. for (var x = -1; x < 2; x++) {
  77203. for (var y = -1; y < 2; y++) {
  77204. downSampleOffsets[id] = x / lastLuminance.width;
  77205. downSampleOffsets[id + 1] = y / lastLuminance.height;
  77206. id += 2;
  77207. }
  77208. }
  77209. effect.setArray2("dsOffsets", downSampleOffsets);
  77210. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  77211. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  77212. lastLuminance = _this.luminancePostProcess;
  77213. }
  77214. else {
  77215. lastLuminance = pp;
  77216. }
  77217. };
  77218. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  77219. pp.onAfterRender = function (effect) {
  77220. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  77221. 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);
  77222. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  77223. };
  77224. }
  77225. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  77226. });
  77227. };
  77228. // Create HDR post-process
  77229. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  77230. var _this = this;
  77231. 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);
  77232. var outputLiminance = 1;
  77233. var time = 0;
  77234. var lastTime = 0;
  77235. this.hdrPostProcess.onApply = function (effect) {
  77236. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  77237. time += scene.getEngine().getDeltaTime();
  77238. if (outputLiminance < 0) {
  77239. outputLiminance = _this._hdrCurrentLuminance;
  77240. }
  77241. else {
  77242. var dt = (lastTime - time) / 1000.0;
  77243. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  77244. outputLiminance += _this.hdrDecreaseRate * dt;
  77245. }
  77246. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  77247. outputLiminance -= _this.hdrIncreaseRate * dt;
  77248. }
  77249. else {
  77250. outputLiminance = _this._hdrCurrentLuminance;
  77251. }
  77252. }
  77253. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  77254. effect.setFloat("averageLuminance", outputLiminance);
  77255. lastTime = time;
  77256. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  77257. };
  77258. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  77259. };
  77260. // Create lens flare post-process
  77261. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  77262. var _this = this;
  77263. 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);
  77264. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  77265. this._createBlurPostProcesses(scene, ratio / 4, 2);
  77266. 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);
  77267. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  77268. var resolution = new BABYLON.Vector2(0, 0);
  77269. // Lens flare
  77270. this.lensFlarePostProcess.onApply = function (effect) {
  77271. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  77272. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  77273. effect.setFloat("strength", _this.lensFlareStrength);
  77274. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  77275. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  77276. // Shift
  77277. resolution.x = _this.lensFlarePostProcess.width;
  77278. resolution.y = _this.lensFlarePostProcess.height;
  77279. effect.setVector2("resolution", resolution);
  77280. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  77281. };
  77282. // Compose
  77283. 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);
  77284. 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);
  77285. this.lensFlareComposePostProcess.onApply = function (effect) {
  77286. if (!_this._scene.activeCamera) {
  77287. return;
  77288. }
  77289. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  77290. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  77291. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  77292. // Lens start rotation matrix
  77293. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  77294. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  77295. 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));
  77296. camRot *= 4.0;
  77297. 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);
  77298. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  77299. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  77300. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  77301. };
  77302. };
  77303. // Create depth-of-field post-process
  77304. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  77305. var _this = this;
  77306. 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);
  77307. this.depthOfFieldPostProcess.onApply = function (effect) {
  77308. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  77309. effect.setTexture("depthSampler", _this._getDepthTexture());
  77310. effect.setFloat("distance", _this.depthOfFieldDistance);
  77311. };
  77312. // Add to pipeline
  77313. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  77314. };
  77315. // Create motion blur post-process
  77316. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  77317. var _this = this;
  77318. 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);
  77319. var motionScale = 0;
  77320. var prevViewProjection = BABYLON.Matrix.Identity();
  77321. var invViewProjection = BABYLON.Matrix.Identity();
  77322. var viewProjection = BABYLON.Matrix.Identity();
  77323. var screenSize = BABYLON.Vector2.Zero();
  77324. this.motionBlurPostProcess.onApply = function (effect) {
  77325. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  77326. viewProjection.invertToRef(invViewProjection);
  77327. effect.setMatrix("inverseViewProjection", invViewProjection);
  77328. effect.setMatrix("prevViewProjection", prevViewProjection);
  77329. prevViewProjection = viewProjection;
  77330. screenSize.x = _this.motionBlurPostProcess.width;
  77331. screenSize.y = _this.motionBlurPostProcess.height;
  77332. effect.setVector2("screenSize", screenSize);
  77333. motionScale = scene.getEngine().getFps() / 60.0;
  77334. effect.setFloat("motionScale", motionScale);
  77335. effect.setFloat("motionStrength", _this.motionStrength);
  77336. effect.setTexture("depthSampler", _this._getDepthTexture());
  77337. };
  77338. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  77339. };
  77340. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  77341. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  77342. var renderer = this._scene.enableGeometryBufferRenderer();
  77343. return renderer.getGBuffer().textures[0];
  77344. }
  77345. return this._scene.enableDepthRenderer().getDepthMap();
  77346. };
  77347. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  77348. for (var i = 0; i < this._cameras.length; i++) {
  77349. var camera = this._cameras[i];
  77350. if (this.originalPostProcess) {
  77351. this.originalPostProcess.dispose(camera);
  77352. }
  77353. if (this.downSampleX4PostProcess) {
  77354. this.downSampleX4PostProcess.dispose(camera);
  77355. }
  77356. if (this.brightPassPostProcess) {
  77357. this.brightPassPostProcess.dispose(camera);
  77358. }
  77359. if (this.textureAdderPostProcess) {
  77360. this.textureAdderPostProcess.dispose(camera);
  77361. }
  77362. if (this.textureAdderFinalPostProcess) {
  77363. this.textureAdderFinalPostProcess.dispose(camera);
  77364. }
  77365. if (this.volumetricLightPostProcess) {
  77366. this.volumetricLightPostProcess.dispose(camera);
  77367. }
  77368. if (this.volumetricLightSmoothXPostProcess) {
  77369. this.volumetricLightSmoothXPostProcess.dispose(camera);
  77370. }
  77371. if (this.volumetricLightSmoothYPostProcess) {
  77372. this.volumetricLightSmoothYPostProcess.dispose(camera);
  77373. }
  77374. if (this.volumetricLightMergePostProces) {
  77375. this.volumetricLightMergePostProces.dispose(camera);
  77376. }
  77377. if (this.volumetricLightFinalPostProcess) {
  77378. this.volumetricLightFinalPostProcess.dispose(camera);
  77379. }
  77380. if (this.lensFlarePostProcess) {
  77381. this.lensFlarePostProcess.dispose(camera);
  77382. }
  77383. if (this.lensFlareComposePostProcess) {
  77384. this.lensFlareComposePostProcess.dispose(camera);
  77385. }
  77386. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  77387. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  77388. }
  77389. if (this.luminancePostProcess) {
  77390. this.luminancePostProcess.dispose(camera);
  77391. }
  77392. if (this.hdrPostProcess) {
  77393. this.hdrPostProcess.dispose(camera);
  77394. }
  77395. if (this.hdrFinalPostProcess) {
  77396. this.hdrFinalPostProcess.dispose(camera);
  77397. }
  77398. if (this.depthOfFieldPostProcess) {
  77399. this.depthOfFieldPostProcess.dispose(camera);
  77400. }
  77401. if (this.motionBlurPostProcess) {
  77402. this.motionBlurPostProcess.dispose(camera);
  77403. }
  77404. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  77405. this.blurHPostProcesses[j].dispose(camera);
  77406. }
  77407. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  77408. this.blurVPostProcesses[j].dispose(camera);
  77409. }
  77410. }
  77411. this.originalPostProcess = null;
  77412. this.downSampleX4PostProcess = null;
  77413. this.brightPassPostProcess = null;
  77414. this.textureAdderPostProcess = null;
  77415. this.textureAdderFinalPostProcess = null;
  77416. this.volumetricLightPostProcess = null;
  77417. this.volumetricLightSmoothXPostProcess = null;
  77418. this.volumetricLightSmoothYPostProcess = null;
  77419. this.volumetricLightMergePostProces = null;
  77420. this.volumetricLightFinalPostProcess = null;
  77421. this.lensFlarePostProcess = null;
  77422. this.lensFlareComposePostProcess = null;
  77423. this.luminancePostProcess = null;
  77424. this.hdrPostProcess = null;
  77425. this.hdrFinalPostProcess = null;
  77426. this.depthOfFieldPostProcess = null;
  77427. this.motionBlurPostProcess = null;
  77428. this.luminanceDownSamplePostProcesses = [];
  77429. this.blurHPostProcesses = [];
  77430. this.blurVPostProcesses = [];
  77431. };
  77432. /**
  77433. * Dispose of the pipeline and stop all post processes
  77434. */
  77435. StandardRenderingPipeline.prototype.dispose = function () {
  77436. this._disposePostProcesses();
  77437. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77438. _super.prototype.dispose.call(this);
  77439. };
  77440. /**
  77441. * Serialize the rendering pipeline (Used when exporting)
  77442. * @returns the serialized object
  77443. */
  77444. StandardRenderingPipeline.prototype.serialize = function () {
  77445. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77446. if (this.sourceLight) {
  77447. serializationObject.sourceLightId = this.sourceLight.id;
  77448. }
  77449. serializationObject.customType = "StandardRenderingPipeline";
  77450. return serializationObject;
  77451. };
  77452. /**
  77453. * Parse the serialized pipeline
  77454. * @param source Source pipeline.
  77455. * @param scene The scene to load the pipeline to.
  77456. * @param rootUrl The URL of the serialized pipeline.
  77457. * @returns An instantiated pipeline from the serialized object.
  77458. */
  77459. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  77460. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  77461. if (source.sourceLightId) {
  77462. p.sourceLight = scene.getLightByID(source.sourceLightId);
  77463. }
  77464. return p;
  77465. };
  77466. // Luminance steps
  77467. StandardRenderingPipeline.LuminanceSteps = 6;
  77468. __decorate([
  77469. BABYLON.serialize()
  77470. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  77471. __decorate([
  77472. BABYLON.serialize()
  77473. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  77474. __decorate([
  77475. BABYLON.serialize()
  77476. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  77477. __decorate([
  77478. BABYLON.serialize()
  77479. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  77480. __decorate([
  77481. BABYLON.serializeAsTexture("lensTexture")
  77482. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  77483. __decorate([
  77484. BABYLON.serialize()
  77485. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  77486. __decorate([
  77487. BABYLON.serialize()
  77488. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  77489. __decorate([
  77490. BABYLON.serialize()
  77491. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  77492. __decorate([
  77493. BABYLON.serialize()
  77494. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  77495. __decorate([
  77496. BABYLON.serialize()
  77497. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  77498. __decorate([
  77499. BABYLON.serialize()
  77500. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  77501. __decorate([
  77502. BABYLON.serializeAsTexture("lensColorTexture")
  77503. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  77504. __decorate([
  77505. BABYLON.serialize()
  77506. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  77507. __decorate([
  77508. BABYLON.serialize()
  77509. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  77510. __decorate([
  77511. BABYLON.serialize()
  77512. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  77513. __decorate([
  77514. BABYLON.serialize()
  77515. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  77516. __decorate([
  77517. BABYLON.serializeAsTexture("lensStarTexture")
  77518. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  77519. __decorate([
  77520. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  77521. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  77522. __decorate([
  77523. BABYLON.serialize()
  77524. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  77525. __decorate([
  77526. BABYLON.serialize()
  77527. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  77528. __decorate([
  77529. BABYLON.serialize()
  77530. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  77531. __decorate([
  77532. BABYLON.serialize()
  77533. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  77534. __decorate([
  77535. BABYLON.serialize()
  77536. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  77537. __decorate([
  77538. BABYLON.serialize()
  77539. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  77540. __decorate([
  77541. BABYLON.serialize()
  77542. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  77543. __decorate([
  77544. BABYLON.serialize()
  77545. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  77546. __decorate([
  77547. BABYLON.serialize()
  77548. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  77549. __decorate([
  77550. BABYLON.serialize()
  77551. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  77552. __decorate([
  77553. BABYLON.serialize()
  77554. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  77555. __decorate([
  77556. BABYLON.serialize()
  77557. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  77558. return StandardRenderingPipeline;
  77559. }(BABYLON.PostProcessRenderPipeline));
  77560. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  77561. })(BABYLON || (BABYLON = {}));
  77562. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  77563. var BABYLON;
  77564. (function (BABYLON) {
  77565. var FxaaPostProcess = /** @class */ (function (_super) {
  77566. __extends(FxaaPostProcess, _super);
  77567. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77568. if (camera === void 0) { camera = null; }
  77569. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77570. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  77571. var defines = _this._getDefines();
  77572. _this.updateEffect(defines);
  77573. _this.onApplyObservable.add(function (effect) {
  77574. var texelSize = _this.texelSize;
  77575. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  77576. });
  77577. return _this;
  77578. }
  77579. FxaaPostProcess.prototype._getDefines = function () {
  77580. var engine = this.getEngine();
  77581. if (!engine) {
  77582. return null;
  77583. }
  77584. var glInfo = engine.getGlInfo();
  77585. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  77586. return "#define MALI 1\n";
  77587. }
  77588. return null;
  77589. };
  77590. return FxaaPostProcess;
  77591. }(BABYLON.PostProcess));
  77592. BABYLON.FxaaPostProcess = FxaaPostProcess;
  77593. })(BABYLON || (BABYLON = {}));
  77594. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  77595. var BABYLON;
  77596. (function (BABYLON) {
  77597. /**
  77598. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  77599. */
  77600. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  77601. __extends(ChromaticAberrationPostProcess, _super);
  77602. /**
  77603. * Creates a new instance ChromaticAberrationPostProcess
  77604. * @param name The name of the effect.
  77605. * @param screenWidth The width of the screen to apply the effect on.
  77606. * @param screenHeight The height of the screen to apply the effect on.
  77607. * @param options The required width/height ratio to downsize to before computing the render pass.
  77608. * @param camera The camera to apply the render pass to.
  77609. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77610. * @param engine The engine which the post process will be applied. (default: current engine)
  77611. * @param reusable If the post process can be reused on the same frame. (default: false)
  77612. * @param textureType Type of textures used when performing the post process. (default: 0)
  77613. * @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)
  77614. */
  77615. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77616. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77617. if (blockCompilation === void 0) { blockCompilation = false; }
  77618. 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;
  77619. /**
  77620. * The amount of seperation of rgb channels (default: 30)
  77621. */
  77622. _this.aberrationAmount = 30;
  77623. /**
  77624. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  77625. */
  77626. _this.radialIntensity = 0;
  77627. /**
  77628. * 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))
  77629. */
  77630. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  77631. /**
  77632. * 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))
  77633. */
  77634. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  77635. _this.onApplyObservable.add(function (effect) {
  77636. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  77637. effect.setFloat('screen_width', screenWidth);
  77638. effect.setFloat('screen_height', screenHeight);
  77639. effect.setFloat('radialIntensity', _this.radialIntensity);
  77640. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  77641. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  77642. });
  77643. return _this;
  77644. }
  77645. return ChromaticAberrationPostProcess;
  77646. }(BABYLON.PostProcess));
  77647. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  77648. })(BABYLON || (BABYLON = {}));
  77649. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  77650. var BABYLON;
  77651. (function (BABYLON) {
  77652. /**
  77653. * The GrainPostProcess adds noise to the image at mid luminance levels
  77654. */
  77655. var GrainPostProcess = /** @class */ (function (_super) {
  77656. __extends(GrainPostProcess, _super);
  77657. /**
  77658. * Creates a new instance of @see GrainPostProcess
  77659. * @param name The name of the effect.
  77660. * @param options The required width/height ratio to downsize to before computing the render pass.
  77661. * @param camera The camera to apply the render pass to.
  77662. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77663. * @param engine The engine which the post process will be applied. (default: current engine)
  77664. * @param reusable If the post process can be reused on the same frame. (default: false)
  77665. * @param textureType Type of textures used when performing the post process. (default: 0)
  77666. * @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)
  77667. */
  77668. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77669. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77670. if (blockCompilation === void 0) { blockCompilation = false; }
  77671. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77672. /**
  77673. * The intensity of the grain added (default: 30)
  77674. */
  77675. _this.intensity = 30;
  77676. /**
  77677. * If the grain should be randomized on every frame
  77678. */
  77679. _this.animated = false;
  77680. _this.onApplyObservable.add(function (effect) {
  77681. effect.setFloat('intensity', _this.intensity);
  77682. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  77683. });
  77684. return _this;
  77685. }
  77686. return GrainPostProcess;
  77687. }(BABYLON.PostProcess));
  77688. BABYLON.GrainPostProcess = GrainPostProcess;
  77689. })(BABYLON || (BABYLON = {}));
  77690. //# sourceMappingURL=babylon.grainPostProcess.js.map
  77691. var BABYLON;
  77692. (function (BABYLON) {
  77693. /**
  77694. * The SharpenPostProcess applies a sharpen kernel to every pixel
  77695. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77696. */
  77697. var SharpenPostProcess = /** @class */ (function (_super) {
  77698. __extends(SharpenPostProcess, _super);
  77699. /**
  77700. * Creates a new instance ConvolutionPostProcess
  77701. * @param name The name of the effect.
  77702. * @param options The required width/height ratio to downsize to before computing the render pass.
  77703. * @param camera The camera to apply the render pass to.
  77704. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77705. * @param engine The engine which the post process will be applied. (default: current engine)
  77706. * @param reusable If the post process can be reused on the same frame. (default: false)
  77707. * @param textureType Type of textures used when performing the post process. (default: 0)
  77708. * @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)
  77709. */
  77710. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77711. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77712. if (blockCompilation === void 0) { blockCompilation = false; }
  77713. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77714. /**
  77715. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  77716. */
  77717. _this.colorAmount = 1.0;
  77718. /**
  77719. * How much sharpness should be applied (default: 0.3)
  77720. */
  77721. _this.edgeAmount = 0.3;
  77722. _this.onApply = function (effect) {
  77723. effect.setFloat2("screenSize", _this.width, _this.height);
  77724. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  77725. };
  77726. return _this;
  77727. }
  77728. return SharpenPostProcess;
  77729. }(BABYLON.PostProcess));
  77730. BABYLON.SharpenPostProcess = SharpenPostProcess;
  77731. })(BABYLON || (BABYLON = {}));
  77732. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  77733. var BABYLON;
  77734. (function (BABYLON) {
  77735. /**
  77736. * The Blur Post Process which blurs an image based on a kernel and direction.
  77737. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  77738. */
  77739. var BlurPostProcess = /** @class */ (function (_super) {
  77740. __extends(BlurPostProcess, _super);
  77741. /**
  77742. * Creates a new instance BlurPostProcess
  77743. * @param name The name of the effect.
  77744. * @param direction The direction in which to blur the image.
  77745. * @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.
  77746. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  77747. * @param camera The camera to apply the render pass to.
  77748. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77749. * @param engine The engine which the post process will be applied. (default: current engine)
  77750. * @param reusable If the post process can be reused on the same frame. (default: false)
  77751. * @param textureType Type of textures used when performing the post process. (default: 0)
  77752. * @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)
  77753. */
  77754. function BlurPostProcess(name,
  77755. /** The direction in which to blur the image. */
  77756. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  77757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77758. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77759. if (defines === void 0) { defines = ""; }
  77760. if (blockCompilation === void 0) { blockCompilation = false; }
  77761. 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;
  77762. _this.direction = direction;
  77763. _this.blockCompilation = blockCompilation;
  77764. _this._packedFloat = false;
  77765. _this._staticDefines = "";
  77766. _this._staticDefines = defines;
  77767. _this.onApplyObservable.add(function (effect) {
  77768. if (_this._outputTexture) {
  77769. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  77770. }
  77771. else {
  77772. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  77773. }
  77774. });
  77775. _this.kernel = kernel;
  77776. return _this;
  77777. }
  77778. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  77779. /**
  77780. * Gets the length in pixels of the blur sample region
  77781. */
  77782. get: function () {
  77783. return this._idealKernel;
  77784. },
  77785. /**
  77786. * Sets the length in pixels of the blur sample region
  77787. */
  77788. set: function (v) {
  77789. if (this._idealKernel === v) {
  77790. return;
  77791. }
  77792. v = Math.max(v, 1);
  77793. this._idealKernel = v;
  77794. this._kernel = this._nearestBestKernel(v);
  77795. if (!this.blockCompilation) {
  77796. this._updateParameters();
  77797. }
  77798. },
  77799. enumerable: true,
  77800. configurable: true
  77801. });
  77802. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  77803. /**
  77804. * Gets wether or not the blur is unpacking/repacking floats
  77805. */
  77806. get: function () {
  77807. return this._packedFloat;
  77808. },
  77809. /**
  77810. * Sets wether or not the blur needs to unpack/repack floats
  77811. */
  77812. set: function (v) {
  77813. if (this._packedFloat === v) {
  77814. return;
  77815. }
  77816. this._packedFloat = v;
  77817. if (!this.blockCompilation) {
  77818. this._updateParameters();
  77819. }
  77820. },
  77821. enumerable: true,
  77822. configurable: true
  77823. });
  77824. /**
  77825. * Updates the effect with the current post process compile time values and recompiles the shader.
  77826. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77827. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77828. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77829. * @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
  77830. * @param onCompiled Called when the shader has been compiled.
  77831. * @param onError Called if there is an error when compiling a shader.
  77832. */
  77833. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77834. if (defines === void 0) { defines = null; }
  77835. if (uniforms === void 0) { uniforms = null; }
  77836. if (samplers === void 0) { samplers = null; }
  77837. this._updateParameters(onCompiled, onError);
  77838. };
  77839. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  77840. // Generate sampling offsets and weights
  77841. var N = this._kernel;
  77842. var centerIndex = (N - 1) / 2;
  77843. // Generate Gaussian sampling weights over kernel
  77844. var offsets = [];
  77845. var weights = [];
  77846. var totalWeight = 0;
  77847. for (var i = 0; i < N; i++) {
  77848. var u = i / (N - 1);
  77849. var w = this._gaussianWeight(u * 2.0 - 1);
  77850. offsets[i] = (i - centerIndex);
  77851. weights[i] = w;
  77852. totalWeight += w;
  77853. }
  77854. // Normalize weights
  77855. for (var i = 0; i < weights.length; i++) {
  77856. weights[i] /= totalWeight;
  77857. }
  77858. // Optimize: combine samples to take advantage of hardware linear sampling
  77859. // Walk from left to center, combining pairs (symmetrically)
  77860. var linearSamplingWeights = [];
  77861. var linearSamplingOffsets = [];
  77862. var linearSamplingMap = [];
  77863. for (var i = 0; i <= centerIndex; i += 2) {
  77864. var j = Math.min(i + 1, Math.floor(centerIndex));
  77865. var singleCenterSample = i === j;
  77866. if (singleCenterSample) {
  77867. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  77868. }
  77869. else {
  77870. var sharedCell = j === centerIndex;
  77871. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  77872. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  77873. if (offsetLinear === 0) {
  77874. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  77875. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  77876. }
  77877. else {
  77878. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  77879. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  77880. }
  77881. }
  77882. }
  77883. for (var i = 0; i < linearSamplingMap.length; i++) {
  77884. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  77885. linearSamplingWeights[i] = linearSamplingMap[i].w;
  77886. }
  77887. // Replace with optimized
  77888. offsets = linearSamplingOffsets;
  77889. weights = linearSamplingWeights;
  77890. // Generate shaders
  77891. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  77892. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  77893. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  77894. var defines = "";
  77895. defines += this._staticDefines;
  77896. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  77897. if (this._staticDefines.indexOf("DOF") != -1) {
  77898. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  77899. varyingCount--;
  77900. }
  77901. for (var i = 0; i < varyingCount; i++) {
  77902. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  77903. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  77904. }
  77905. var depCount = 0;
  77906. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  77907. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  77908. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  77909. depCount++;
  77910. }
  77911. if (this.packedFloat) {
  77912. defines += "#define PACKEDFLOAT 1";
  77913. }
  77914. this.blockCompilation = false;
  77915. _super.prototype.updateEffect.call(this, defines, null, null, {
  77916. varyingCount: varyingCount,
  77917. depCount: depCount
  77918. }, onCompiled, onError);
  77919. };
  77920. /**
  77921. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  77922. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  77923. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  77924. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  77925. * The gaps between physical kernels are compensated for in the weighting of the samples
  77926. * @param idealKernel Ideal blur kernel.
  77927. * @return Nearest best kernel.
  77928. */
  77929. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  77930. var v = Math.round(idealKernel);
  77931. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  77932. var k = _a[_i];
  77933. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  77934. return Math.max(k, 3);
  77935. }
  77936. }
  77937. return Math.max(v, 3);
  77938. };
  77939. /**
  77940. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  77941. * @param x The point on the Gaussian distribution to sample.
  77942. * @return the value of the Gaussian function at x.
  77943. */
  77944. BlurPostProcess.prototype._gaussianWeight = function (x) {
  77945. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  77946. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  77947. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  77948. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  77949. // truncated at around 1.3% of peak strength.
  77950. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  77951. var sigma = (1 / 3);
  77952. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  77953. var exponent = -((x * x) / (2.0 * sigma * sigma));
  77954. var weight = (1.0 / denominator) * Math.exp(exponent);
  77955. return weight;
  77956. };
  77957. /**
  77958. * Generates a string that can be used as a floating point number in GLSL.
  77959. * @param x Value to print.
  77960. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  77961. * @return GLSL float string.
  77962. */
  77963. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  77964. if (decimalFigures === void 0) { decimalFigures = 8; }
  77965. return x.toFixed(decimalFigures).replace(/0+$/, '');
  77966. };
  77967. return BlurPostProcess;
  77968. }(BABYLON.PostProcess));
  77969. BABYLON.BlurPostProcess = BlurPostProcess;
  77970. })(BABYLON || (BABYLON = {}));
  77971. //# sourceMappingURL=babylon.blurPostProcess.js.map
  77972. var BABYLON;
  77973. (function (BABYLON) {
  77974. /**
  77975. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  77976. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  77977. * based on samples that have a large difference in distance than the center pixel.
  77978. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77979. */
  77980. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  77981. __extends(DepthOfFieldBlurPostProcess, _super);
  77982. /**
  77983. * Creates a new instance CircleOfConfusionPostProcess
  77984. * @param name The name of the effect.
  77985. * @param scene The scene the effect belongs to.
  77986. * @param direction The direction the blur should be applied.
  77987. * @param kernel The size of the kernel used to blur.
  77988. * @param options The required width/height ratio to downsize to before computing the render pass.
  77989. * @param camera The camera to apply the render pass to.
  77990. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  77991. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  77992. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77993. * @param engine The engine which the post process will be applied. (default: current engine)
  77994. * @param reusable If the post process can be reused on the same frame. (default: false)
  77995. * @param textureType Type of textures used when performing the post process. (default: 0)
  77996. * @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)
  77997. */
  77998. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  77999. if (imageToBlur === void 0) { imageToBlur = null; }
  78000. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78001. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78002. if (blockCompilation === void 0) { blockCompilation = false; }
  78003. 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;
  78004. _this.direction = direction;
  78005. _this.onApplyObservable.add(function (effect) {
  78006. if (imageToBlur != null) {
  78007. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  78008. }
  78009. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  78010. if (scene.activeCamera) {
  78011. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  78012. }
  78013. });
  78014. return _this;
  78015. }
  78016. return DepthOfFieldBlurPostProcess;
  78017. }(BABYLON.BlurPostProcess));
  78018. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  78019. })(BABYLON || (BABYLON = {}));
  78020. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  78021. var BABYLON;
  78022. (function (BABYLON) {
  78023. /**
  78024. * Options to be set when merging outputs from the default pipeline.
  78025. */
  78026. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  78027. function DepthOfFieldMergePostProcessOptions() {
  78028. }
  78029. return DepthOfFieldMergePostProcessOptions;
  78030. }());
  78031. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  78032. /**
  78033. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  78034. */
  78035. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  78036. __extends(DepthOfFieldMergePostProcess, _super);
  78037. /**
  78038. * Creates a new instance of DepthOfFieldMergePostProcess
  78039. * @param name The name of the effect.
  78040. * @param originalFromInput Post process which's input will be used for the merge.
  78041. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  78042. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  78043. * @param options The required width/height ratio to downsize to before computing the render pass.
  78044. * @param camera The camera to apply the render pass to.
  78045. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78046. * @param engine The engine which the post process will be applied. (default: current engine)
  78047. * @param reusable If the post process can be reused on the same frame. (default: false)
  78048. * @param textureType Type of textures used when performing the post process. (default: 0)
  78049. * @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)
  78050. */
  78051. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78052. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78053. if (blockCompilation === void 0) { blockCompilation = false; }
  78054. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  78055. _this.blurSteps = blurSteps;
  78056. _this.onApplyObservable.add(function (effect) {
  78057. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  78058. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  78059. blurSteps.forEach(function (step, index) {
  78060. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  78061. });
  78062. });
  78063. if (!blockCompilation) {
  78064. _this.updateEffect();
  78065. }
  78066. return _this;
  78067. }
  78068. /**
  78069. * Updates the effect with the current post process compile time values and recompiles the shader.
  78070. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  78071. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  78072. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  78073. * @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
  78074. * @param onCompiled Called when the shader has been compiled.
  78075. * @param onError Called if there is an error when compiling a shader.
  78076. */
  78077. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  78078. if (defines === void 0) { defines = null; }
  78079. if (uniforms === void 0) { uniforms = null; }
  78080. if (samplers === void 0) { samplers = null; }
  78081. if (!defines) {
  78082. defines = "";
  78083. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  78084. }
  78085. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  78086. };
  78087. return DepthOfFieldMergePostProcess;
  78088. }(BABYLON.PostProcess));
  78089. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  78090. })(BABYLON || (BABYLON = {}));
  78091. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  78092. var BABYLON;
  78093. (function (BABYLON) {
  78094. /**
  78095. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  78096. */
  78097. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  78098. __extends(CircleOfConfusionPostProcess, _super);
  78099. /**
  78100. * Creates a new instance CircleOfConfusionPostProcess
  78101. * @param name The name of the effect.
  78102. * @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.
  78103. * @param options The required width/height ratio to downsize to before computing the render pass.
  78104. * @param camera The camera to apply the render pass to.
  78105. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78106. * @param engine The engine which the post process will be applied. (default: current engine)
  78107. * @param reusable If the post process can be reused on the same frame. (default: false)
  78108. * @param textureType Type of textures used when performing the post process. (default: 0)
  78109. * @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)
  78110. */
  78111. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78112. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78113. if (blockCompilation === void 0) { blockCompilation = false; }
  78114. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78115. /**
  78116. * 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.
  78117. */
  78118. _this.lensSize = 50;
  78119. /**
  78120. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  78121. */
  78122. _this.fStop = 1.4;
  78123. /**
  78124. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  78125. */
  78126. _this.focusDistance = 2000;
  78127. /**
  78128. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  78129. */
  78130. _this.focalLength = 50;
  78131. _this._depthTexture = null;
  78132. _this._depthTexture = depthTexture;
  78133. _this.onApplyObservable.add(function (effect) {
  78134. if (!_this._depthTexture) {
  78135. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  78136. return;
  78137. }
  78138. effect.setTexture("depthSampler", _this._depthTexture);
  78139. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  78140. var aperture = _this.lensSize / _this.fStop;
  78141. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  78142. effect.setFloat('focusDistance', _this.focusDistance);
  78143. effect.setFloat('cocPrecalculation', cocPrecalculation);
  78144. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  78145. });
  78146. return _this;
  78147. }
  78148. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  78149. /**
  78150. * 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.
  78151. */
  78152. set: function (value) {
  78153. this._depthTexture = value;
  78154. },
  78155. enumerable: true,
  78156. configurable: true
  78157. });
  78158. return CircleOfConfusionPostProcess;
  78159. }(BABYLON.PostProcess));
  78160. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  78161. })(BABYLON || (BABYLON = {}));
  78162. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  78163. var BABYLON;
  78164. (function (BABYLON) {
  78165. /**
  78166. * Specifies the level of max blur that should be applied when using the depth of field effect
  78167. */
  78168. var DepthOfFieldEffectBlurLevel;
  78169. (function (DepthOfFieldEffectBlurLevel) {
  78170. /**
  78171. * Subtle blur
  78172. */
  78173. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  78174. /**
  78175. * Medium blur
  78176. */
  78177. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  78178. /**
  78179. * Large blur
  78180. */
  78181. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  78182. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  78183. ;
  78184. /**
  78185. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  78186. */
  78187. var DepthOfFieldEffect = /** @class */ (function (_super) {
  78188. __extends(DepthOfFieldEffect, _super);
  78189. /**
  78190. * Creates a new instance DepthOfFieldEffect
  78191. * @param scene The scene the effect belongs to.
  78192. * @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.
  78193. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  78194. * @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)
  78195. */
  78196. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  78197. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  78198. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  78199. if (blockCompilation === void 0) { blockCompilation = false; }
  78200. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  78201. return _this._effects;
  78202. }, true) || this;
  78203. /**
  78204. * @hidden Internal post processes in depth of field effect
  78205. */
  78206. _this._effects = [];
  78207. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  78208. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78209. // 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)
  78210. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  78211. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  78212. _this._depthOfFieldBlurY = [];
  78213. _this._depthOfFieldBlurX = [];
  78214. var blurCount = 1;
  78215. var kernelSize = 15;
  78216. switch (blurLevel) {
  78217. case DepthOfFieldEffectBlurLevel.High: {
  78218. blurCount = 3;
  78219. kernelSize = 51;
  78220. break;
  78221. }
  78222. case DepthOfFieldEffectBlurLevel.Medium: {
  78223. blurCount = 2;
  78224. kernelSize = 31;
  78225. break;
  78226. }
  78227. default: {
  78228. kernelSize = 15;
  78229. blurCount = 1;
  78230. break;
  78231. }
  78232. }
  78233. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  78234. var ratio = 1.0;
  78235. for (var i = 0; i < blurCount; i++) {
  78236. 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);
  78237. blurY.autoClear = false;
  78238. ratio = 0.75 / Math.pow(2, i);
  78239. 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);
  78240. blurX.autoClear = false;
  78241. _this._depthOfFieldBlurY.push(blurY);
  78242. _this._depthOfFieldBlurX.push(blurX);
  78243. }
  78244. // Set all post processes on the effect.
  78245. _this._effects = [_this._circleOfConfusion];
  78246. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  78247. _this._effects.push(_this._depthOfFieldBlurY[i]);
  78248. _this._effects.push(_this._depthOfFieldBlurX[i]);
  78249. }
  78250. // Merge blurred images with original image based on circleOfConfusion
  78251. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78252. _this._dofMerge.autoClear = false;
  78253. _this._effects.push(_this._dofMerge);
  78254. return _this;
  78255. }
  78256. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  78257. get: function () {
  78258. return this._circleOfConfusion.focalLength;
  78259. },
  78260. /**
  78261. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  78262. */
  78263. set: function (value) {
  78264. this._circleOfConfusion.focalLength = value;
  78265. },
  78266. enumerable: true,
  78267. configurable: true
  78268. });
  78269. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  78270. get: function () {
  78271. return this._circleOfConfusion.fStop;
  78272. },
  78273. /**
  78274. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  78275. */
  78276. set: function (value) {
  78277. this._circleOfConfusion.fStop = value;
  78278. },
  78279. enumerable: true,
  78280. configurable: true
  78281. });
  78282. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  78283. get: function () {
  78284. return this._circleOfConfusion.focusDistance;
  78285. },
  78286. /**
  78287. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  78288. */
  78289. set: function (value) {
  78290. this._circleOfConfusion.focusDistance = value;
  78291. },
  78292. enumerable: true,
  78293. configurable: true
  78294. });
  78295. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  78296. get: function () {
  78297. return this._circleOfConfusion.lensSize;
  78298. },
  78299. /**
  78300. * 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.
  78301. */
  78302. set: function (value) {
  78303. this._circleOfConfusion.lensSize = value;
  78304. },
  78305. enumerable: true,
  78306. configurable: true
  78307. });
  78308. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  78309. /**
  78310. * 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.
  78311. */
  78312. set: function (value) {
  78313. this._circleOfConfusion.depthTexture = value;
  78314. },
  78315. enumerable: true,
  78316. configurable: true
  78317. });
  78318. /**
  78319. * Disposes each of the internal effects for a given camera.
  78320. * @param camera The camera to dispose the effect on.
  78321. */
  78322. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  78323. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78324. this._effects[effectIndex].dispose(camera);
  78325. }
  78326. };
  78327. /**
  78328. * @hidden Internal
  78329. */
  78330. DepthOfFieldEffect.prototype._updateEffects = function () {
  78331. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78332. this._effects[effectIndex].updateEffect();
  78333. }
  78334. };
  78335. /**
  78336. * Internal
  78337. * @returns if all the contained post processes are ready.
  78338. * @hidden
  78339. */
  78340. DepthOfFieldEffect.prototype._isReady = function () {
  78341. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78342. if (!this._effects[effectIndex].isReady()) {
  78343. return false;
  78344. }
  78345. }
  78346. return true;
  78347. };
  78348. return DepthOfFieldEffect;
  78349. }(BABYLON.PostProcessRenderEffect));
  78350. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  78351. })(BABYLON || (BABYLON = {}));
  78352. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  78353. var BABYLON;
  78354. (function (BABYLON) {
  78355. /**
  78356. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  78357. */
  78358. var BloomMergePostProcess = /** @class */ (function (_super) {
  78359. __extends(BloomMergePostProcess, _super);
  78360. /**
  78361. * Creates a new instance of @see BloomMergePostProcess
  78362. * @param name The name of the effect.
  78363. * @param originalFromInput Post process which's input will be used for the merge.
  78364. * @param blurred Blurred highlights post process which's output will be used.
  78365. * @param weight Weight of the bloom to be added to the original input.
  78366. * @param options The required width/height ratio to downsize to before computing the render pass.
  78367. * @param camera The camera to apply the render pass to.
  78368. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78369. * @param engine The engine which the post process will be applied. (default: current engine)
  78370. * @param reusable If the post process can be reused on the same frame. (default: false)
  78371. * @param textureType Type of textures used when performing the post process. (default: 0)
  78372. * @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)
  78373. */
  78374. function BloomMergePostProcess(name, originalFromInput, blurred,
  78375. /** Weight of the bloom to be added to the original input. */
  78376. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78377. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78378. if (blockCompilation === void 0) { blockCompilation = false; }
  78379. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  78380. _this.weight = weight;
  78381. _this.onApplyObservable.add(function (effect) {
  78382. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  78383. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  78384. effect.setFloat("bloomWeight", _this.weight);
  78385. });
  78386. if (!blockCompilation) {
  78387. _this.updateEffect();
  78388. }
  78389. return _this;
  78390. }
  78391. return BloomMergePostProcess;
  78392. }(BABYLON.PostProcess));
  78393. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  78394. })(BABYLON || (BABYLON = {}));
  78395. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  78396. var BABYLON;
  78397. (function (BABYLON) {
  78398. /**
  78399. * 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.
  78400. */
  78401. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  78402. __extends(ExtractHighlightsPostProcess, _super);
  78403. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78404. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78405. if (blockCompilation === void 0) { blockCompilation = false; }
  78406. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78407. /**
  78408. * The luminance threshold, pixels below this value will be set to black.
  78409. */
  78410. _this.threshold = 0.9;
  78411. /** @hidden */
  78412. _this._exposure = 1;
  78413. /**
  78414. * Post process which has the input texture to be used when performing highlight extraction
  78415. * @hidden
  78416. */
  78417. _this._inputPostProcess = null;
  78418. _this.onApplyObservable.add(function (effect) {
  78419. if (_this._inputPostProcess) {
  78420. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  78421. }
  78422. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  78423. effect.setFloat('exposure', _this._exposure);
  78424. });
  78425. return _this;
  78426. }
  78427. return ExtractHighlightsPostProcess;
  78428. }(BABYLON.PostProcess));
  78429. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  78430. })(BABYLON || (BABYLON = {}));
  78431. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  78432. var BABYLON;
  78433. (function (BABYLON) {
  78434. /**
  78435. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  78436. */
  78437. var BloomEffect = /** @class */ (function (_super) {
  78438. __extends(BloomEffect, _super);
  78439. /**
  78440. * Creates a new instance of @see BloomEffect
  78441. * @param scene The scene the effect belongs to.
  78442. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  78443. * @param bloomKernel The size of the kernel to be used when applying the blur.
  78444. * @param bloomWeight The the strength of bloom.
  78445. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  78446. * @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)
  78447. */
  78448. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  78449. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  78450. if (blockCompilation === void 0) { blockCompilation = false; }
  78451. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  78452. return _this._effects;
  78453. }, true) || this;
  78454. _this.bloomScale = bloomScale;
  78455. /**
  78456. * @hidden Internal
  78457. */
  78458. _this._effects = [];
  78459. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78460. _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);
  78461. _this._blurX.alwaysForcePOT = true;
  78462. _this._blurX.autoClear = false;
  78463. _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);
  78464. _this._blurY.alwaysForcePOT = true;
  78465. _this._blurY.autoClear = false;
  78466. _this.kernel = bloomKernel;
  78467. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  78468. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78469. _this._merge.autoClear = false;
  78470. _this._effects.push(_this._merge);
  78471. return _this;
  78472. }
  78473. Object.defineProperty(BloomEffect.prototype, "threshold", {
  78474. /**
  78475. * The luminance threshold to find bright areas of the image to bloom.
  78476. */
  78477. get: function () {
  78478. return this._downscale.threshold;
  78479. },
  78480. set: function (value) {
  78481. this._downscale.threshold = value;
  78482. },
  78483. enumerable: true,
  78484. configurable: true
  78485. });
  78486. Object.defineProperty(BloomEffect.prototype, "weight", {
  78487. /**
  78488. * The strength of the bloom.
  78489. */
  78490. get: function () {
  78491. return this._merge.weight;
  78492. },
  78493. set: function (value) {
  78494. this._merge.weight = value;
  78495. },
  78496. enumerable: true,
  78497. configurable: true
  78498. });
  78499. Object.defineProperty(BloomEffect.prototype, "kernel", {
  78500. /**
  78501. * Specifies the size of the bloom blur kernel, relative to the final output size
  78502. */
  78503. get: function () {
  78504. return this._blurX.kernel / this.bloomScale;
  78505. },
  78506. set: function (value) {
  78507. this._blurX.kernel = value * this.bloomScale;
  78508. this._blurY.kernel = value * this.bloomScale;
  78509. },
  78510. enumerable: true,
  78511. configurable: true
  78512. });
  78513. /**
  78514. * Disposes each of the internal effects for a given camera.
  78515. * @param camera The camera to dispose the effect on.
  78516. */
  78517. BloomEffect.prototype.disposeEffects = function (camera) {
  78518. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78519. this._effects[effectIndex].dispose(camera);
  78520. }
  78521. };
  78522. /**
  78523. * @hidden Internal
  78524. */
  78525. BloomEffect.prototype._updateEffects = function () {
  78526. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78527. this._effects[effectIndex].updateEffect();
  78528. }
  78529. };
  78530. /**
  78531. * Internal
  78532. * @returns if all the contained post processes are ready.
  78533. * @hidden
  78534. */
  78535. BloomEffect.prototype._isReady = function () {
  78536. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78537. if (!this._effects[effectIndex].isReady()) {
  78538. return false;
  78539. }
  78540. }
  78541. return true;
  78542. };
  78543. return BloomEffect;
  78544. }(BABYLON.PostProcessRenderEffect));
  78545. BABYLON.BloomEffect = BloomEffect;
  78546. })(BABYLON || (BABYLON = {}));
  78547. //# sourceMappingURL=babylon.bloomEffect.js.map
  78548. var BABYLON;
  78549. (function (BABYLON) {
  78550. /**
  78551. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  78552. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  78553. */
  78554. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  78555. __extends(DefaultRenderingPipeline, _super);
  78556. /**
  78557. * @constructor
  78558. * @param {string} name - The rendering pipeline name (default: "")
  78559. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  78560. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  78561. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  78562. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  78563. */
  78564. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  78565. if (name === void 0) { name = ""; }
  78566. if (hdr === void 0) { hdr = true; }
  78567. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78568. if (automaticBuild === void 0) { automaticBuild = true; }
  78569. var _this = _super.call(this, scene.getEngine(), name) || this;
  78570. _this._camerasToBeAttached = [];
  78571. /**
  78572. * ID of the sharpen post process,
  78573. */
  78574. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  78575. /**
  78576. * ID of the image processing post process;
  78577. */
  78578. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  78579. /**
  78580. * ID of the Fast Approximate Anti-Aliasing post process;
  78581. */
  78582. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  78583. /**
  78584. * ID of the chromatic aberration post process,
  78585. */
  78586. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  78587. /**
  78588. * ID of the grain post process
  78589. */
  78590. _this.GrainPostProcessId = "GrainPostProcessEffect";
  78591. /**
  78592. * Glow post process which adds a glow to emmisive areas of the image
  78593. */
  78594. _this._glowLayer = null;
  78595. /**
  78596. * Animations which can be used to tweak settings over a period of time
  78597. */
  78598. _this.animations = [];
  78599. _this._imageProcessingConfigurationObserver = null;
  78600. // Values
  78601. _this._sharpenEnabled = false;
  78602. _this._bloomEnabled = false;
  78603. _this._depthOfFieldEnabled = false;
  78604. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  78605. _this._fxaaEnabled = false;
  78606. _this._imageProcessingEnabled = true;
  78607. _this._bloomScale = 0.5;
  78608. _this._chromaticAberrationEnabled = false;
  78609. _this._grainEnabled = false;
  78610. _this._buildAllowed = true;
  78611. _this._resizeObserver = null;
  78612. _this._hardwareScaleLevel = 1.0;
  78613. _this._bloomKernel = 64;
  78614. /**
  78615. * Specifies the weight of the bloom in the final rendering
  78616. */
  78617. _this._bloomWeight = 0.15;
  78618. /**
  78619. * Specifies the luma threshold for the area that will be blurred by the bloom
  78620. */
  78621. _this._bloomThreshold = 0.9;
  78622. _this._samples = 1;
  78623. _this._hasCleared = false;
  78624. _this._prevPostProcess = null;
  78625. _this._prevPrevPostProcess = null;
  78626. _this._cameras = cameras || scene.cameras;
  78627. _this._cameras = _this._cameras.slice();
  78628. _this._camerasToBeAttached = _this._cameras.slice();
  78629. _this._buildAllowed = automaticBuild;
  78630. // Initialize
  78631. _this._scene = scene;
  78632. var caps = _this._scene.getEngine().getCaps();
  78633. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  78634. // Misc
  78635. if (_this._hdr) {
  78636. if (caps.textureHalfFloatRender) {
  78637. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78638. }
  78639. else if (caps.textureFloatRender) {
  78640. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78641. }
  78642. }
  78643. else {
  78644. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78645. }
  78646. // Attach
  78647. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78648. var engine = _this._scene.getEngine();
  78649. // Create post processes before hand so they can be modified before enabled.
  78650. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  78651. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78652. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  78653. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  78654. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  78655. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78656. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  78657. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78658. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  78659. _this._resizeObserver = engine.onResizeObservable.add(function () {
  78660. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  78661. _this.bloomKernel = _this.bloomKernel;
  78662. });
  78663. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  78664. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  78665. });
  78666. _this._buildPipeline();
  78667. return _this;
  78668. }
  78669. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  78670. get: function () {
  78671. return this._sharpenEnabled;
  78672. },
  78673. /**
  78674. * Enable or disable the sharpen process from the pipeline
  78675. */
  78676. set: function (enabled) {
  78677. if (this._sharpenEnabled === enabled) {
  78678. return;
  78679. }
  78680. this._sharpenEnabled = enabled;
  78681. this._buildPipeline();
  78682. },
  78683. enumerable: true,
  78684. configurable: true
  78685. });
  78686. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  78687. /**
  78688. * Specifies the size of the bloom blur kernel, relative to the final output size
  78689. */
  78690. get: function () {
  78691. return this._bloomKernel;
  78692. },
  78693. set: function (value) {
  78694. this._bloomKernel = value;
  78695. this.bloom.kernel = value / this._hardwareScaleLevel;
  78696. },
  78697. enumerable: true,
  78698. configurable: true
  78699. });
  78700. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  78701. get: function () {
  78702. return this._bloomWeight;
  78703. },
  78704. /**
  78705. * The strength of the bloom.
  78706. */
  78707. set: function (value) {
  78708. if (this._bloomWeight === value) {
  78709. return;
  78710. }
  78711. this.bloom.weight = value;
  78712. this._bloomWeight = value;
  78713. },
  78714. enumerable: true,
  78715. configurable: true
  78716. });
  78717. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  78718. get: function () {
  78719. return this._bloomThreshold;
  78720. },
  78721. /**
  78722. * The strength of the bloom.
  78723. */
  78724. set: function (value) {
  78725. if (this._bloomThreshold === value) {
  78726. return;
  78727. }
  78728. this.bloom.threshold = value;
  78729. this._bloomThreshold = value;
  78730. },
  78731. enumerable: true,
  78732. configurable: true
  78733. });
  78734. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  78735. get: function () {
  78736. return this._bloomScale;
  78737. },
  78738. /**
  78739. * The scale of the bloom, lower value will provide better performance.
  78740. */
  78741. set: function (value) {
  78742. if (this._bloomScale === value) {
  78743. return;
  78744. }
  78745. this._bloomScale = value;
  78746. // recreate bloom and dispose old as this setting is not dynamic
  78747. this._rebuildBloom();
  78748. this._buildPipeline();
  78749. },
  78750. enumerable: true,
  78751. configurable: true
  78752. });
  78753. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  78754. get: function () {
  78755. return this._bloomEnabled;
  78756. },
  78757. /**
  78758. * Enable or disable the bloom from the pipeline
  78759. */
  78760. set: function (enabled) {
  78761. if (this._bloomEnabled === enabled) {
  78762. return;
  78763. }
  78764. this._bloomEnabled = enabled;
  78765. this._buildPipeline();
  78766. },
  78767. enumerable: true,
  78768. configurable: true
  78769. });
  78770. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  78771. // recreate bloom and dispose old as this setting is not dynamic
  78772. var oldBloom = this.bloom;
  78773. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  78774. this.bloom.threshold = oldBloom.threshold;
  78775. for (var i = 0; i < this._cameras.length; i++) {
  78776. oldBloom.disposeEffects(this._cameras[i]);
  78777. }
  78778. };
  78779. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  78780. /**
  78781. * If the depth of field is enabled.
  78782. */
  78783. get: function () {
  78784. return this._depthOfFieldEnabled;
  78785. },
  78786. set: function (enabled) {
  78787. if (this._depthOfFieldEnabled === enabled) {
  78788. return;
  78789. }
  78790. this._depthOfFieldEnabled = enabled;
  78791. this._buildPipeline();
  78792. },
  78793. enumerable: true,
  78794. configurable: true
  78795. });
  78796. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  78797. /**
  78798. * Blur level of the depth of field effect. (Higher blur will effect performance)
  78799. */
  78800. get: function () {
  78801. return this._depthOfFieldBlurLevel;
  78802. },
  78803. set: function (value) {
  78804. if (this._depthOfFieldBlurLevel === value) {
  78805. return;
  78806. }
  78807. this._depthOfFieldBlurLevel = value;
  78808. // recreate dof and dispose old as this setting is not dynamic
  78809. var oldDof = this.depthOfField;
  78810. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  78811. this.depthOfField.focalLength = oldDof.focalLength;
  78812. this.depthOfField.focusDistance = oldDof.focusDistance;
  78813. this.depthOfField.fStop = oldDof.fStop;
  78814. this.depthOfField.lensSize = oldDof.lensSize;
  78815. for (var i = 0; i < this._cameras.length; i++) {
  78816. oldDof.disposeEffects(this._cameras[i]);
  78817. }
  78818. this._buildPipeline();
  78819. },
  78820. enumerable: true,
  78821. configurable: true
  78822. });
  78823. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  78824. get: function () {
  78825. return this._fxaaEnabled;
  78826. },
  78827. /**
  78828. * If the anti aliasing is enabled.
  78829. */
  78830. set: function (enabled) {
  78831. if (this._fxaaEnabled === enabled) {
  78832. return;
  78833. }
  78834. this._fxaaEnabled = enabled;
  78835. this._buildPipeline();
  78836. },
  78837. enumerable: true,
  78838. configurable: true
  78839. });
  78840. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  78841. get: function () {
  78842. return this._samples;
  78843. },
  78844. /**
  78845. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  78846. */
  78847. set: function (sampleCount) {
  78848. if (this._samples === sampleCount) {
  78849. return;
  78850. }
  78851. this._samples = sampleCount;
  78852. this._buildPipeline();
  78853. },
  78854. enumerable: true,
  78855. configurable: true
  78856. });
  78857. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  78858. get: function () {
  78859. return this._imageProcessingEnabled;
  78860. },
  78861. /**
  78862. * If image processing is enabled.
  78863. */
  78864. set: function (enabled) {
  78865. if (this._imageProcessingEnabled === enabled) {
  78866. return;
  78867. }
  78868. this._imageProcessingEnabled = enabled;
  78869. this._buildPipeline();
  78870. },
  78871. enumerable: true,
  78872. configurable: true
  78873. });
  78874. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  78875. get: function () {
  78876. return this._glowLayer == null;
  78877. },
  78878. /**
  78879. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  78880. */
  78881. set: function (enabled) {
  78882. if (enabled && !this._glowLayer) {
  78883. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  78884. }
  78885. else if (!enabled && this._glowLayer) {
  78886. this._glowLayer.dispose();
  78887. this._glowLayer = null;
  78888. }
  78889. },
  78890. enumerable: true,
  78891. configurable: true
  78892. });
  78893. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  78894. get: function () {
  78895. return this._chromaticAberrationEnabled;
  78896. },
  78897. /**
  78898. * Enable or disable the chromaticAberration process from the pipeline
  78899. */
  78900. set: function (enabled) {
  78901. if (this._chromaticAberrationEnabled === enabled) {
  78902. return;
  78903. }
  78904. this._chromaticAberrationEnabled = enabled;
  78905. this._buildPipeline();
  78906. },
  78907. enumerable: true,
  78908. configurable: true
  78909. });
  78910. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  78911. get: function () {
  78912. return this._grainEnabled;
  78913. },
  78914. /**
  78915. * Enable or disable the grain process from the pipeline
  78916. */
  78917. set: function (enabled) {
  78918. if (this._grainEnabled === enabled) {
  78919. return;
  78920. }
  78921. this._grainEnabled = enabled;
  78922. this._buildPipeline();
  78923. },
  78924. enumerable: true,
  78925. configurable: true
  78926. });
  78927. /**
  78928. * Force the compilation of the entire pipeline.
  78929. */
  78930. DefaultRenderingPipeline.prototype.prepare = function () {
  78931. var previousState = this._buildAllowed;
  78932. this._buildAllowed = true;
  78933. this._buildPipeline();
  78934. this._buildAllowed = previousState;
  78935. };
  78936. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  78937. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  78938. if (this._hasCleared) {
  78939. postProcess.autoClear = false;
  78940. }
  78941. else {
  78942. postProcess.autoClear = true;
  78943. this._scene.autoClear = false;
  78944. this._hasCleared = true;
  78945. }
  78946. if (!skipTextureSharing) {
  78947. if (this._prevPrevPostProcess) {
  78948. postProcess.shareOutputWith(this._prevPrevPostProcess);
  78949. }
  78950. else {
  78951. postProcess.useOwnOutput();
  78952. }
  78953. if (this._prevPostProcess) {
  78954. this._prevPrevPostProcess = this._prevPostProcess;
  78955. }
  78956. this._prevPostProcess = postProcess;
  78957. }
  78958. };
  78959. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  78960. var _this = this;
  78961. if (!this._buildAllowed) {
  78962. return;
  78963. }
  78964. this._scene.autoClear = true;
  78965. var engine = this._scene.getEngine();
  78966. this._disposePostProcesses();
  78967. if (this._cameras !== null) {
  78968. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78969. // get back cameras to be used to reattach pipeline
  78970. this._cameras = this._camerasToBeAttached.slice();
  78971. }
  78972. this._reset();
  78973. this._prevPostProcess = null;
  78974. this._prevPrevPostProcess = null;
  78975. this._hasCleared = false;
  78976. if (this.depthOfFieldEnabled) {
  78977. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  78978. this.depthOfField.depthTexture = depthTexture;
  78979. if (!this.depthOfField._isReady()) {
  78980. this.depthOfField._updateEffects();
  78981. }
  78982. this.addEffect(this.depthOfField);
  78983. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  78984. }
  78985. if (this.bloomEnabled) {
  78986. if (!this.bloom._isReady()) {
  78987. this.bloom._updateEffects();
  78988. }
  78989. this.addEffect(this.bloom);
  78990. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  78991. }
  78992. if (this._imageProcessingEnabled) {
  78993. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78994. if (this._hdr) {
  78995. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  78996. this._setAutoClearAndTextureSharing(this.imageProcessing);
  78997. }
  78998. else {
  78999. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  79000. }
  79001. }
  79002. if (this.sharpenEnabled) {
  79003. if (!this.sharpen.isReady()) {
  79004. this.sharpen.updateEffect();
  79005. }
  79006. this.addEffect(this._sharpenEffect);
  79007. this._setAutoClearAndTextureSharing(this.sharpen);
  79008. }
  79009. if (this.grainEnabled) {
  79010. if (!this.grain.isReady()) {
  79011. this.grain.updateEffect();
  79012. }
  79013. this.addEffect(this._grainEffect);
  79014. this._setAutoClearAndTextureSharing(this.grain);
  79015. }
  79016. if (this.chromaticAberrationEnabled) {
  79017. if (!this.chromaticAberration.isReady()) {
  79018. this.chromaticAberration.updateEffect();
  79019. }
  79020. this.addEffect(this._chromaticAberrationEffect);
  79021. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  79022. }
  79023. if (this.fxaaEnabled) {
  79024. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  79025. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  79026. this._setAutoClearAndTextureSharing(this.fxaa, true);
  79027. }
  79028. if (this._cameras !== null) {
  79029. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  79030. }
  79031. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  79032. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  79033. }
  79034. };
  79035. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  79036. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  79037. for (var i = 0; i < this._cameras.length; i++) {
  79038. var camera = this._cameras[i];
  79039. if (this.imageProcessing) {
  79040. this.imageProcessing.dispose(camera);
  79041. }
  79042. if (this.fxaa) {
  79043. this.fxaa.dispose(camera);
  79044. }
  79045. // These are created in the constructor and should not be disposed on every pipeline change
  79046. if (disposeNonRecreated) {
  79047. if (this.sharpen) {
  79048. this.sharpen.dispose(camera);
  79049. }
  79050. if (this.depthOfField) {
  79051. this.depthOfField.disposeEffects(camera);
  79052. }
  79053. if (this.bloom) {
  79054. this.bloom.disposeEffects(camera);
  79055. }
  79056. if (this.chromaticAberration) {
  79057. this.chromaticAberration.dispose(camera);
  79058. }
  79059. if (this.grain) {
  79060. this.grain.dispose(camera);
  79061. }
  79062. if (this._glowLayer) {
  79063. this._glowLayer.dispose();
  79064. }
  79065. }
  79066. }
  79067. this.imageProcessing = null;
  79068. this.fxaa = null;
  79069. if (disposeNonRecreated) {
  79070. this.sharpen = null;
  79071. this._sharpenEffect = null;
  79072. this.depthOfField = null;
  79073. this.bloom = null;
  79074. this.chromaticAberration = null;
  79075. this._chromaticAberrationEffect = null;
  79076. this.grain = null;
  79077. this._grainEffect = null;
  79078. this._glowLayer = null;
  79079. }
  79080. };
  79081. /**
  79082. * Adds a camera to the pipeline
  79083. * @param camera the camera to be added
  79084. */
  79085. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  79086. this._camerasToBeAttached.push(camera);
  79087. this._buildPipeline();
  79088. };
  79089. /**
  79090. * Removes a camera from the pipeline
  79091. * @param camera the camera to remove
  79092. */
  79093. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  79094. var index = this._camerasToBeAttached.indexOf(camera);
  79095. this._camerasToBeAttached.splice(index, 1);
  79096. this._buildPipeline();
  79097. };
  79098. /**
  79099. * Dispose of the pipeline and stop all post processes
  79100. */
  79101. DefaultRenderingPipeline.prototype.dispose = function () {
  79102. this._disposePostProcesses(true);
  79103. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79104. this._scene.autoClear = true;
  79105. if (this._resizeObserver) {
  79106. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  79107. this._resizeObserver = null;
  79108. }
  79109. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  79110. _super.prototype.dispose.call(this);
  79111. };
  79112. /**
  79113. * Serialize the rendering pipeline (Used when exporting)
  79114. * @returns the serialized object
  79115. */
  79116. DefaultRenderingPipeline.prototype.serialize = function () {
  79117. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79118. serializationObject.customType = "DefaultRenderingPipeline";
  79119. return serializationObject;
  79120. };
  79121. /**
  79122. * Parse the serialized pipeline
  79123. * @param source Source pipeline.
  79124. * @param scene The scene to load the pipeline to.
  79125. * @param rootUrl The URL of the serialized pipeline.
  79126. * @returns An instantiated pipeline from the serialized object.
  79127. */
  79128. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  79129. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  79130. };
  79131. __decorate([
  79132. BABYLON.serialize()
  79133. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  79134. __decorate([
  79135. BABYLON.serialize()
  79136. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  79137. __decorate([
  79138. BABYLON.serialize()
  79139. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  79140. __decorate([
  79141. BABYLON.serialize()
  79142. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  79143. __decorate([
  79144. BABYLON.serialize()
  79145. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  79146. __decorate([
  79147. BABYLON.serialize()
  79148. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  79149. __decorate([
  79150. BABYLON.serialize()
  79151. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  79152. __decorate([
  79153. BABYLON.serialize()
  79154. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  79155. __decorate([
  79156. BABYLON.serialize()
  79157. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  79158. __decorate([
  79159. BABYLON.serialize()
  79160. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  79161. __decorate([
  79162. BABYLON.serialize()
  79163. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  79164. __decorate([
  79165. BABYLON.serialize()
  79166. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  79167. __decorate([
  79168. BABYLON.serialize()
  79169. ], DefaultRenderingPipeline.prototype, "samples", null);
  79170. __decorate([
  79171. BABYLON.serialize()
  79172. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  79173. __decorate([
  79174. BABYLON.serialize()
  79175. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  79176. __decorate([
  79177. BABYLON.serialize()
  79178. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  79179. __decorate([
  79180. BABYLON.serialize()
  79181. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  79182. return DefaultRenderingPipeline;
  79183. }(BABYLON.PostProcessRenderPipeline));
  79184. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  79185. })(BABYLON || (BABYLON = {}));
  79186. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  79187. var BABYLON;
  79188. (function (BABYLON) {
  79189. /**
  79190. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  79191. */
  79192. var GeometryBufferRenderer = /** @class */ (function () {
  79193. /**
  79194. * Creates a new G Buffer for the scene
  79195. * @param scene The scene the buffer belongs to
  79196. * @param ratio How big is the buffer related to the main canvas.
  79197. */
  79198. function GeometryBufferRenderer(scene, ratio) {
  79199. if (ratio === void 0) { ratio = 1; }
  79200. this._enablePosition = false;
  79201. this._scene = scene;
  79202. this._ratio = ratio;
  79203. // Render target
  79204. this._createRenderTargets();
  79205. }
  79206. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  79207. /**
  79208. * Set the render list (meshes to be rendered) used in the G buffer.
  79209. */
  79210. set: function (meshes) {
  79211. this._multiRenderTarget.renderList = meshes;
  79212. },
  79213. enumerable: true,
  79214. configurable: true
  79215. });
  79216. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  79217. /**
  79218. * Gets wether or not G buffer are supported by the running hardware.
  79219. * This requires draw buffer supports
  79220. */
  79221. get: function () {
  79222. return this._multiRenderTarget.isSupported;
  79223. },
  79224. enumerable: true,
  79225. configurable: true
  79226. });
  79227. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  79228. /**
  79229. * Gets wether or not position are enabled for the G buffer.
  79230. */
  79231. get: function () {
  79232. return this._enablePosition;
  79233. },
  79234. /**
  79235. * Sets wether or not position are enabled for the G buffer.
  79236. */
  79237. set: function (enable) {
  79238. this._enablePosition = enable;
  79239. this.dispose();
  79240. this._createRenderTargets();
  79241. },
  79242. enumerable: true,
  79243. configurable: true
  79244. });
  79245. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  79246. /**
  79247. * Gets the scene associated with the buffer.
  79248. */
  79249. get: function () {
  79250. return this._scene;
  79251. },
  79252. enumerable: true,
  79253. configurable: true
  79254. });
  79255. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  79256. /**
  79257. * Gets the ratio used by the buffer during its creation.
  79258. * How big is the buffer related to the main canvas.
  79259. */
  79260. get: function () {
  79261. return this._ratio;
  79262. },
  79263. enumerable: true,
  79264. configurable: true
  79265. });
  79266. /**
  79267. * Checks wether everything is ready to render a submesh to the G buffer.
  79268. * @param subMesh the submesh to check readiness for
  79269. * @param useInstances is the mesh drawn using instance or not
  79270. * @returns true if ready otherwise false
  79271. */
  79272. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  79273. var material = subMesh.getMaterial();
  79274. if (material && material.disableDepthWrite) {
  79275. return false;
  79276. }
  79277. var defines = [];
  79278. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79279. var mesh = subMesh.getMesh();
  79280. // Alpha test
  79281. if (material && material.needAlphaTesting()) {
  79282. defines.push("#define ALPHATEST");
  79283. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79284. attribs.push(BABYLON.VertexBuffer.UVKind);
  79285. defines.push("#define UV1");
  79286. }
  79287. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79288. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79289. defines.push("#define UV2");
  79290. }
  79291. }
  79292. // Buffers
  79293. if (this._enablePosition) {
  79294. defines.push("#define POSITION");
  79295. }
  79296. // Bones
  79297. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79298. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79299. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79300. if (mesh.numBoneInfluencers > 4) {
  79301. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79302. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79303. }
  79304. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79305. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79306. }
  79307. else {
  79308. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79309. }
  79310. // Instances
  79311. if (useInstances) {
  79312. defines.push("#define INSTANCES");
  79313. attribs.push("world0");
  79314. attribs.push("world1");
  79315. attribs.push("world2");
  79316. attribs.push("world3");
  79317. }
  79318. // Get correct effect
  79319. var join = defines.join("\n");
  79320. if (this._cachedDefines !== join) {
  79321. this._cachedDefines = join;
  79322. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  79323. }
  79324. return this._effect.isReady();
  79325. };
  79326. /**
  79327. * Gets the current underlying G Buffer.
  79328. * @returns the buffer
  79329. */
  79330. GeometryBufferRenderer.prototype.getGBuffer = function () {
  79331. return this._multiRenderTarget;
  79332. };
  79333. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  79334. /**
  79335. * Gets the number of samples used to render the buffer (anti aliasing).
  79336. */
  79337. get: function () {
  79338. return this._multiRenderTarget.samples;
  79339. },
  79340. /**
  79341. * Sets the number of samples used to render the buffer (anti aliasing).
  79342. */
  79343. set: function (value) {
  79344. this._multiRenderTarget.samples = value;
  79345. },
  79346. enumerable: true,
  79347. configurable: true
  79348. });
  79349. /**
  79350. * Disposes the renderer and frees up associated resources.
  79351. */
  79352. GeometryBufferRenderer.prototype.dispose = function () {
  79353. this.getGBuffer().dispose();
  79354. };
  79355. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  79356. var _this = this;
  79357. var engine = this._scene.getEngine();
  79358. var count = this._enablePosition ? 3 : 2;
  79359. 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 });
  79360. if (!this.isSupported) {
  79361. return;
  79362. }
  79363. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79364. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79365. this._multiRenderTarget.refreshRate = 1;
  79366. this._multiRenderTarget.renderParticles = false;
  79367. this._multiRenderTarget.renderList = null;
  79368. // set default depth value to 1.0 (far away)
  79369. this._multiRenderTarget.onClearObservable.add(function (engine) {
  79370. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  79371. });
  79372. // Custom render function
  79373. var renderSubMesh = function (subMesh) {
  79374. var mesh = subMesh.getRenderingMesh();
  79375. var scene = _this._scene;
  79376. var engine = scene.getEngine();
  79377. var material = subMesh.getMaterial();
  79378. if (!material) {
  79379. return;
  79380. }
  79381. // Culling
  79382. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  79383. // Managing instances
  79384. var batch = mesh._getInstancesRenderList(subMesh._id);
  79385. if (batch.mustReturn) {
  79386. return;
  79387. }
  79388. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79389. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  79390. engine.enableEffect(_this._effect);
  79391. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  79392. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79393. _this._effect.setMatrix("view", scene.getViewMatrix());
  79394. // Alpha test
  79395. if (material && material.needAlphaTesting()) {
  79396. var alphaTexture = material.getAlphaTestTexture();
  79397. if (alphaTexture) {
  79398. _this._effect.setTexture("diffuseSampler", alphaTexture);
  79399. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79400. }
  79401. }
  79402. // Bones
  79403. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79404. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79405. }
  79406. // Draw
  79407. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  79408. }
  79409. };
  79410. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79411. var index;
  79412. if (depthOnlySubMeshes.length) {
  79413. engine.setColorWrite(false);
  79414. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79415. renderSubMesh(depthOnlySubMeshes.data[index]);
  79416. }
  79417. engine.setColorWrite(true);
  79418. }
  79419. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79420. renderSubMesh(opaqueSubMeshes.data[index]);
  79421. }
  79422. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79423. renderSubMesh(alphaTestSubMeshes.data[index]);
  79424. }
  79425. };
  79426. };
  79427. return GeometryBufferRenderer;
  79428. }());
  79429. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  79430. })(BABYLON || (BABYLON = {}));
  79431. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  79432. var BABYLON;
  79433. (function (BABYLON) {
  79434. /**
  79435. * @hidden
  79436. */
  79437. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  79438. __extends(ImageProcessingConfigurationDefines, _super);
  79439. function ImageProcessingConfigurationDefines() {
  79440. var _this = _super.call(this) || this;
  79441. _this.IMAGEPROCESSING = false;
  79442. _this.VIGNETTE = false;
  79443. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  79444. _this.VIGNETTEBLENDMODEOPAQUE = false;
  79445. _this.TONEMAPPING = false;
  79446. _this.TONEMAPPING_ACES = false;
  79447. _this.CONTRAST = false;
  79448. _this.COLORCURVES = false;
  79449. _this.COLORGRADING = false;
  79450. _this.COLORGRADING3D = false;
  79451. _this.SAMPLER3DGREENDEPTH = false;
  79452. _this.SAMPLER3DBGRMAP = false;
  79453. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  79454. _this.EXPOSURE = false;
  79455. _this.rebuild();
  79456. return _this;
  79457. }
  79458. return ImageProcessingConfigurationDefines;
  79459. }(BABYLON.MaterialDefines));
  79460. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  79461. /**
  79462. * This groups together the common properties used for image processing either in direct forward pass
  79463. * or through post processing effect depending on the use of the image processing pipeline in your scene
  79464. * or not.
  79465. */
  79466. var ImageProcessingConfiguration = /** @class */ (function () {
  79467. function ImageProcessingConfiguration() {
  79468. /**
  79469. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  79470. */
  79471. this.colorCurves = new BABYLON.ColorCurves();
  79472. this._colorCurvesEnabled = false;
  79473. this._colorGradingEnabled = false;
  79474. this._colorGradingWithGreenDepth = true;
  79475. this._colorGradingBGR = true;
  79476. /** @hidden */
  79477. this._exposure = 1.0;
  79478. this._toneMappingEnabled = false;
  79479. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  79480. this._contrast = 1.0;
  79481. /**
  79482. * Vignette stretch size.
  79483. */
  79484. this.vignetteStretch = 0;
  79485. /**
  79486. * Vignette centre X Offset.
  79487. */
  79488. this.vignetteCentreX = 0;
  79489. /**
  79490. * Vignette centre Y Offset.
  79491. */
  79492. this.vignetteCentreY = 0;
  79493. /**
  79494. * Vignette weight or intensity of the vignette effect.
  79495. */
  79496. this.vignetteWeight = 1.5;
  79497. /**
  79498. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79499. * if vignetteEnabled is set to true.
  79500. */
  79501. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79502. /**
  79503. * Camera field of view used by the Vignette effect.
  79504. */
  79505. this.vignetteCameraFov = 0.5;
  79506. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  79507. this._vignetteEnabled = false;
  79508. this._applyByPostProcess = false;
  79509. this._isEnabled = true;
  79510. /**
  79511. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  79512. */
  79513. this.onUpdateParameters = new BABYLON.Observable();
  79514. }
  79515. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  79516. /**
  79517. * Gets wether the color curves effect is enabled.
  79518. */
  79519. get: function () {
  79520. return this._colorCurvesEnabled;
  79521. },
  79522. /**
  79523. * Sets wether the color curves effect is enabled.
  79524. */
  79525. set: function (value) {
  79526. if (this._colorCurvesEnabled === value) {
  79527. return;
  79528. }
  79529. this._colorCurvesEnabled = value;
  79530. this._updateParameters();
  79531. },
  79532. enumerable: true,
  79533. configurable: true
  79534. });
  79535. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  79536. /**
  79537. * Gets wether the color grading effect is enabled.
  79538. */
  79539. get: function () {
  79540. return this._colorGradingEnabled;
  79541. },
  79542. /**
  79543. * Sets wether the color grading effect is enabled.
  79544. */
  79545. set: function (value) {
  79546. if (this._colorGradingEnabled === value) {
  79547. return;
  79548. }
  79549. this._colorGradingEnabled = value;
  79550. this._updateParameters();
  79551. },
  79552. enumerable: true,
  79553. configurable: true
  79554. });
  79555. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  79556. /**
  79557. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  79558. */
  79559. get: function () {
  79560. return this._colorGradingWithGreenDepth;
  79561. },
  79562. /**
  79563. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  79564. */
  79565. set: function (value) {
  79566. if (this._colorGradingWithGreenDepth === value) {
  79567. return;
  79568. }
  79569. this._colorGradingWithGreenDepth = value;
  79570. this._updateParameters();
  79571. },
  79572. enumerable: true,
  79573. configurable: true
  79574. });
  79575. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  79576. /**
  79577. * Gets wether the color grading texture contains BGR values.
  79578. */
  79579. get: function () {
  79580. return this._colorGradingBGR;
  79581. },
  79582. /**
  79583. * Sets wether the color grading texture contains BGR values.
  79584. */
  79585. set: function (value) {
  79586. if (this._colorGradingBGR === value) {
  79587. return;
  79588. }
  79589. this._colorGradingBGR = value;
  79590. this._updateParameters();
  79591. },
  79592. enumerable: true,
  79593. configurable: true
  79594. });
  79595. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  79596. /**
  79597. * Gets the Exposure used in the effect.
  79598. */
  79599. get: function () {
  79600. return this._exposure;
  79601. },
  79602. /**
  79603. * Sets the Exposure used in the effect.
  79604. */
  79605. set: function (value) {
  79606. if (this._exposure === value) {
  79607. return;
  79608. }
  79609. this._exposure = value;
  79610. this._updateParameters();
  79611. },
  79612. enumerable: true,
  79613. configurable: true
  79614. });
  79615. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  79616. /**
  79617. * Gets wether the tone mapping effect is enabled.
  79618. */
  79619. get: function () {
  79620. return this._toneMappingEnabled;
  79621. },
  79622. /**
  79623. * Sets wether the tone mapping effect is enabled.
  79624. */
  79625. set: function (value) {
  79626. if (this._toneMappingEnabled === value) {
  79627. return;
  79628. }
  79629. this._toneMappingEnabled = value;
  79630. this._updateParameters();
  79631. },
  79632. enumerable: true,
  79633. configurable: true
  79634. });
  79635. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  79636. /**
  79637. * Gets the type of tone mapping effect.
  79638. */
  79639. get: function () {
  79640. return this._toneMappingType;
  79641. },
  79642. /**
  79643. * Sets the type of tone mapping effect used in BabylonJS.
  79644. */
  79645. set: function (value) {
  79646. if (this._toneMappingType === value) {
  79647. return;
  79648. }
  79649. this._toneMappingType = value;
  79650. this._updateParameters();
  79651. },
  79652. enumerable: true,
  79653. configurable: true
  79654. });
  79655. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  79656. /**
  79657. * Gets the contrast used in the effect.
  79658. */
  79659. get: function () {
  79660. return this._contrast;
  79661. },
  79662. /**
  79663. * Sets the contrast used in the effect.
  79664. */
  79665. set: function (value) {
  79666. if (this._contrast === value) {
  79667. return;
  79668. }
  79669. this._contrast = value;
  79670. this._updateParameters();
  79671. },
  79672. enumerable: true,
  79673. configurable: true
  79674. });
  79675. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  79676. /**
  79677. * Gets the vignette blend mode allowing different kind of effect.
  79678. */
  79679. get: function () {
  79680. return this._vignetteBlendMode;
  79681. },
  79682. /**
  79683. * Sets the vignette blend mode allowing different kind of effect.
  79684. */
  79685. set: function (value) {
  79686. if (this._vignetteBlendMode === value) {
  79687. return;
  79688. }
  79689. this._vignetteBlendMode = value;
  79690. this._updateParameters();
  79691. },
  79692. enumerable: true,
  79693. configurable: true
  79694. });
  79695. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  79696. /**
  79697. * Gets wether the vignette effect is enabled.
  79698. */
  79699. get: function () {
  79700. return this._vignetteEnabled;
  79701. },
  79702. /**
  79703. * Sets wether the vignette effect is enabled.
  79704. */
  79705. set: function (value) {
  79706. if (this._vignetteEnabled === value) {
  79707. return;
  79708. }
  79709. this._vignetteEnabled = value;
  79710. this._updateParameters();
  79711. },
  79712. enumerable: true,
  79713. configurable: true
  79714. });
  79715. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  79716. /**
  79717. * Gets wether the image processing is applied through a post process or not.
  79718. */
  79719. get: function () {
  79720. return this._applyByPostProcess;
  79721. },
  79722. /**
  79723. * Sets wether the image processing is applied through a post process or not.
  79724. */
  79725. set: function (value) {
  79726. if (this._applyByPostProcess === value) {
  79727. return;
  79728. }
  79729. this._applyByPostProcess = value;
  79730. this._updateParameters();
  79731. },
  79732. enumerable: true,
  79733. configurable: true
  79734. });
  79735. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  79736. /**
  79737. * Gets wether the image processing is enabled or not.
  79738. */
  79739. get: function () {
  79740. return this._isEnabled;
  79741. },
  79742. /**
  79743. * Sets wether the image processing is enabled or not.
  79744. */
  79745. set: function (value) {
  79746. if (this._isEnabled === value) {
  79747. return;
  79748. }
  79749. this._isEnabled = value;
  79750. this._updateParameters();
  79751. },
  79752. enumerable: true,
  79753. configurable: true
  79754. });
  79755. /**
  79756. * Method called each time the image processing information changes requires to recompile the effect.
  79757. */
  79758. ImageProcessingConfiguration.prototype._updateParameters = function () {
  79759. this.onUpdateParameters.notifyObservers(this);
  79760. };
  79761. ImageProcessingConfiguration.prototype.getClassName = function () {
  79762. return "ImageProcessingConfiguration";
  79763. };
  79764. /**
  79765. * Prepare the list of uniforms associated with the Image Processing effects.
  79766. * @param uniformsList The list of uniforms used in the effect
  79767. * @param defines the list of defines currently in use
  79768. */
  79769. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  79770. if (defines.EXPOSURE) {
  79771. uniforms.push("exposureLinear");
  79772. }
  79773. if (defines.CONTRAST) {
  79774. uniforms.push("contrast");
  79775. }
  79776. if (defines.COLORGRADING) {
  79777. uniforms.push("colorTransformSettings");
  79778. }
  79779. if (defines.VIGNETTE) {
  79780. uniforms.push("vInverseScreenSize");
  79781. uniforms.push("vignetteSettings1");
  79782. uniforms.push("vignetteSettings2");
  79783. }
  79784. if (defines.COLORCURVES) {
  79785. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  79786. }
  79787. };
  79788. /**
  79789. * Prepare the list of samplers associated with the Image Processing effects.
  79790. * @param uniformsList The list of uniforms used in the effect
  79791. * @param defines the list of defines currently in use
  79792. */
  79793. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  79794. if (defines.COLORGRADING) {
  79795. samplersList.push("txColorTransform");
  79796. }
  79797. };
  79798. /**
  79799. * Prepare the list of defines associated to the shader.
  79800. * @param defines the list of defines to complete
  79801. */
  79802. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  79803. if (forPostProcess === void 0) { forPostProcess = false; }
  79804. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  79805. defines.VIGNETTE = false;
  79806. defines.TONEMAPPING = false;
  79807. defines.TONEMAPPING_ACES = false;
  79808. defines.CONTRAST = false;
  79809. defines.EXPOSURE = false;
  79810. defines.COLORCURVES = false;
  79811. defines.COLORGRADING = false;
  79812. defines.COLORGRADING3D = false;
  79813. defines.IMAGEPROCESSING = false;
  79814. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  79815. return;
  79816. }
  79817. defines.VIGNETTE = this.vignetteEnabled;
  79818. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  79819. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  79820. defines.TONEMAPPING = this.toneMappingEnabled;
  79821. switch (this._toneMappingType) {
  79822. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  79823. defines.TONEMAPPING_ACES = true;
  79824. break;
  79825. }
  79826. defines.CONTRAST = (this.contrast !== 1.0);
  79827. defines.EXPOSURE = (this.exposure !== 1.0);
  79828. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  79829. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  79830. if (defines.COLORGRADING) {
  79831. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  79832. }
  79833. else {
  79834. defines.COLORGRADING3D = false;
  79835. }
  79836. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  79837. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  79838. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  79839. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  79840. };
  79841. /**
  79842. * Returns true if all the image processing information are ready.
  79843. */
  79844. ImageProcessingConfiguration.prototype.isReady = function () {
  79845. // Color Grading texure can not be none blocking.
  79846. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  79847. };
  79848. /**
  79849. * Binds the image processing to the shader.
  79850. * @param effect The effect to bind to
  79851. */
  79852. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  79853. if (aspectRatio === void 0) { aspectRatio = 1; }
  79854. // Color Curves
  79855. if (this._colorCurvesEnabled && this.colorCurves) {
  79856. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  79857. }
  79858. // Vignette
  79859. if (this._vignetteEnabled) {
  79860. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  79861. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  79862. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  79863. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  79864. var vignetteScaleX = vignetteScaleY * aspectRatio;
  79865. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  79866. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  79867. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  79868. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  79869. var vignettePower = -2.0 * this.vignetteWeight;
  79870. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  79871. }
  79872. // Exposure
  79873. effect.setFloat("exposureLinear", this.exposure);
  79874. // Contrast
  79875. effect.setFloat("contrast", this.contrast);
  79876. // Color transform settings
  79877. if (this.colorGradingTexture) {
  79878. effect.setTexture("txColorTransform", this.colorGradingTexture);
  79879. var textureSize = this.colorGradingTexture.getSize().height;
  79880. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  79881. 0.5 / textureSize, // textureOffset
  79882. textureSize, // textureSize
  79883. this.colorGradingTexture.level // weight
  79884. );
  79885. }
  79886. };
  79887. /**
  79888. * Clones the current image processing instance.
  79889. * @return The cloned image processing
  79890. */
  79891. ImageProcessingConfiguration.prototype.clone = function () {
  79892. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  79893. };
  79894. /**
  79895. * Serializes the current image processing instance to a json representation.
  79896. * @return a JSON representation
  79897. */
  79898. ImageProcessingConfiguration.prototype.serialize = function () {
  79899. return BABYLON.SerializationHelper.Serialize(this);
  79900. };
  79901. /**
  79902. * Parses the image processing from a json representation.
  79903. * @param source the JSON source to parse
  79904. * @return The parsed image processing
  79905. */
  79906. ImageProcessingConfiguration.Parse = function (source) {
  79907. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  79908. };
  79909. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  79910. /**
  79911. * Used to apply the vignette as a mix with the pixel color.
  79912. */
  79913. get: function () {
  79914. return this._VIGNETTEMODE_MULTIPLY;
  79915. },
  79916. enumerable: true,
  79917. configurable: true
  79918. });
  79919. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  79920. /**
  79921. * Used to apply the vignette as a replacement of the pixel color.
  79922. */
  79923. get: function () {
  79924. return this._VIGNETTEMODE_OPAQUE;
  79925. },
  79926. enumerable: true,
  79927. configurable: true
  79928. });
  79929. /**
  79930. * Default tone mapping applied in BabylonJS.
  79931. */
  79932. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  79933. /**
  79934. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  79935. * to other engines rendering to increase portability.
  79936. */
  79937. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  79938. // Static constants associated to the image processing.
  79939. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  79940. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  79941. __decorate([
  79942. BABYLON.serializeAsColorCurves()
  79943. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  79944. __decorate([
  79945. BABYLON.serialize()
  79946. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  79947. __decorate([
  79948. BABYLON.serializeAsTexture()
  79949. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  79950. __decorate([
  79951. BABYLON.serialize()
  79952. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  79953. __decorate([
  79954. BABYLON.serialize()
  79955. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  79956. __decorate([
  79957. BABYLON.serialize()
  79958. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  79959. __decorate([
  79960. BABYLON.serialize()
  79961. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  79962. __decorate([
  79963. BABYLON.serialize()
  79964. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  79965. __decorate([
  79966. BABYLON.serialize()
  79967. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  79968. __decorate([
  79969. BABYLON.serialize()
  79970. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  79971. __decorate([
  79972. BABYLON.serialize()
  79973. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  79974. __decorate([
  79975. BABYLON.serialize()
  79976. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  79977. __decorate([
  79978. BABYLON.serialize()
  79979. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  79980. __decorate([
  79981. BABYLON.serialize()
  79982. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  79983. __decorate([
  79984. BABYLON.serializeAsColor4()
  79985. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  79986. __decorate([
  79987. BABYLON.serialize()
  79988. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  79989. __decorate([
  79990. BABYLON.serialize()
  79991. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  79992. __decorate([
  79993. BABYLON.serialize()
  79994. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  79995. __decorate([
  79996. BABYLON.serialize()
  79997. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  79998. __decorate([
  79999. BABYLON.serialize()
  80000. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  80001. return ImageProcessingConfiguration;
  80002. }());
  80003. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  80004. })(BABYLON || (BABYLON = {}));
  80005. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  80006. var BABYLON;
  80007. (function (BABYLON) {
  80008. /**
  80009. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  80010. * It can help converting any input color in a desired output one. This can then be used to create effects
  80011. * from sepia, black and white to sixties or futuristic rendering...
  80012. *
  80013. * The only supported format is currently 3dl.
  80014. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  80015. */
  80016. var ColorGradingTexture = /** @class */ (function (_super) {
  80017. __extends(ColorGradingTexture, _super);
  80018. /**
  80019. * Instantiates a ColorGradingTexture from the following parameters.
  80020. *
  80021. * @param url The location of the color gradind data (currently only supporting 3dl)
  80022. * @param scene The scene the texture will be used in
  80023. */
  80024. function ColorGradingTexture(url, scene) {
  80025. var _this = _super.call(this, scene) || this;
  80026. if (!url) {
  80027. return _this;
  80028. }
  80029. _this._engine = scene.getEngine();
  80030. _this._textureMatrix = BABYLON.Matrix.Identity();
  80031. _this.name = url;
  80032. _this.url = url;
  80033. _this.hasAlpha = false;
  80034. _this.isCube = false;
  80035. _this.is3D = _this._engine.webGLVersion > 1;
  80036. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80037. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80038. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80039. _this.anisotropicFilteringLevel = 1;
  80040. _this._texture = _this._getFromCache(url, true);
  80041. if (!_this._texture) {
  80042. if (!scene.useDelayedTextureLoading) {
  80043. _this.loadTexture();
  80044. }
  80045. else {
  80046. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80047. }
  80048. }
  80049. return _this;
  80050. }
  80051. /**
  80052. * Returns the texture matrix used in most of the material.
  80053. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  80054. */
  80055. ColorGradingTexture.prototype.getTextureMatrix = function () {
  80056. return this._textureMatrix;
  80057. };
  80058. /**
  80059. * Occurs when the file being loaded is a .3dl LUT file.
  80060. */
  80061. ColorGradingTexture.prototype.load3dlTexture = function () {
  80062. var engine = this._engine;
  80063. var texture;
  80064. if (engine.webGLVersion === 1) {
  80065. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80066. }
  80067. else {
  80068. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80069. }
  80070. this._texture = texture;
  80071. var callback = function (text) {
  80072. if (typeof text !== "string") {
  80073. return;
  80074. }
  80075. var data = null;
  80076. var tempData = null;
  80077. var line;
  80078. var lines = text.split('\n');
  80079. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  80080. var maxColor = 0;
  80081. for (var i = 0; i < lines.length; i++) {
  80082. line = lines[i];
  80083. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  80084. continue;
  80085. if (line.indexOf('#') === 0)
  80086. continue;
  80087. var words = line.split(" ");
  80088. if (size === 0) {
  80089. // Number of space + one
  80090. size = words.length;
  80091. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  80092. tempData = new Float32Array(size * size * size * 4);
  80093. continue;
  80094. }
  80095. if (size != 0) {
  80096. var r = Math.max(parseInt(words[0]), 0);
  80097. var g = Math.max(parseInt(words[1]), 0);
  80098. var b = Math.max(parseInt(words[2]), 0);
  80099. maxColor = Math.max(r, maxColor);
  80100. maxColor = Math.max(g, maxColor);
  80101. maxColor = Math.max(b, maxColor);
  80102. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  80103. if (tempData) {
  80104. tempData[pixelStorageIndex + 0] = r;
  80105. tempData[pixelStorageIndex + 1] = g;
  80106. tempData[pixelStorageIndex + 2] = b;
  80107. }
  80108. pixelIndexSlice++;
  80109. if (pixelIndexSlice % size == 0) {
  80110. pixelIndexH++;
  80111. pixelIndexSlice = 0;
  80112. if (pixelIndexH % size == 0) {
  80113. pixelIndexW++;
  80114. pixelIndexH = 0;
  80115. }
  80116. }
  80117. }
  80118. }
  80119. if (tempData && data) {
  80120. for (var i = 0; i < tempData.length; i++) {
  80121. if (i > 0 && (i + 1) % 4 === 0) {
  80122. data[i] = 255;
  80123. }
  80124. else {
  80125. var value = tempData[i];
  80126. data[i] = (value / maxColor * 255);
  80127. }
  80128. }
  80129. }
  80130. if (texture.is3D) {
  80131. texture.updateSize(size, size, size);
  80132. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80133. }
  80134. else {
  80135. texture.updateSize(size * size, size);
  80136. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80137. }
  80138. };
  80139. var scene = this.getScene();
  80140. if (scene) {
  80141. scene._loadFile(this.url, callback);
  80142. }
  80143. else {
  80144. this._engine._loadFile(this.url, callback);
  80145. }
  80146. return this._texture;
  80147. };
  80148. /**
  80149. * Starts the loading process of the texture.
  80150. */
  80151. ColorGradingTexture.prototype.loadTexture = function () {
  80152. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  80153. this.load3dlTexture();
  80154. }
  80155. };
  80156. /**
  80157. * Clones the color gradind texture.
  80158. */
  80159. ColorGradingTexture.prototype.clone = function () {
  80160. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  80161. // Base texture
  80162. newTexture.level = this.level;
  80163. return newTexture;
  80164. };
  80165. /**
  80166. * Called during delayed load for textures.
  80167. */
  80168. ColorGradingTexture.prototype.delayLoad = function () {
  80169. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80170. return;
  80171. }
  80172. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80173. this._texture = this._getFromCache(this.url, true);
  80174. if (!this._texture) {
  80175. this.loadTexture();
  80176. }
  80177. };
  80178. /**
  80179. * Parses a color grading texture serialized by Babylon.
  80180. * @param parsedTexture The texture information being parsedTexture
  80181. * @param scene The scene to load the texture in
  80182. * @param rootUrl The root url of the data assets to load
  80183. * @return A color gradind texture
  80184. */
  80185. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80186. var texture = null;
  80187. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80188. texture = new ColorGradingTexture(parsedTexture.name, scene);
  80189. texture.name = parsedTexture.name;
  80190. texture.level = parsedTexture.level;
  80191. }
  80192. return texture;
  80193. };
  80194. /**
  80195. * Serializes the LUT texture to json format.
  80196. */
  80197. ColorGradingTexture.prototype.serialize = function () {
  80198. if (!this.name) {
  80199. return null;
  80200. }
  80201. var serializationObject = {};
  80202. serializationObject.name = this.name;
  80203. serializationObject.level = this.level;
  80204. serializationObject.customType = "BABYLON.ColorGradingTexture";
  80205. return serializationObject;
  80206. };
  80207. /**
  80208. * Empty line regex stored for GC.
  80209. */
  80210. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  80211. return ColorGradingTexture;
  80212. }(BABYLON.BaseTexture));
  80213. BABYLON.ColorGradingTexture = ColorGradingTexture;
  80214. })(BABYLON || (BABYLON = {}));
  80215. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  80216. var BABYLON;
  80217. (function (BABYLON) {
  80218. /**
  80219. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80220. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80221. * 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;
  80222. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80223. */
  80224. var ColorCurves = /** @class */ (function () {
  80225. function ColorCurves() {
  80226. this._dirty = true;
  80227. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  80228. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  80229. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  80230. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  80231. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  80232. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  80233. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  80234. this._globalHue = 30;
  80235. this._globalDensity = 0;
  80236. this._globalSaturation = 0;
  80237. this._globalExposure = 0;
  80238. this._highlightsHue = 30;
  80239. this._highlightsDensity = 0;
  80240. this._highlightsSaturation = 0;
  80241. this._highlightsExposure = 0;
  80242. this._midtonesHue = 30;
  80243. this._midtonesDensity = 0;
  80244. this._midtonesSaturation = 0;
  80245. this._midtonesExposure = 0;
  80246. this._shadowsHue = 30;
  80247. this._shadowsDensity = 0;
  80248. this._shadowsSaturation = 0;
  80249. this._shadowsExposure = 0;
  80250. }
  80251. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  80252. /**
  80253. * Gets the global Hue value.
  80254. * 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).
  80255. */
  80256. get: function () {
  80257. return this._globalHue;
  80258. },
  80259. /**
  80260. * Sets the global Hue value.
  80261. * 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).
  80262. */
  80263. set: function (value) {
  80264. this._globalHue = value;
  80265. this._dirty = true;
  80266. },
  80267. enumerable: true,
  80268. configurable: true
  80269. });
  80270. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  80271. /**
  80272. * Gets the global Density value.
  80273. * 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.
  80274. * Values less than zero provide a filter of opposite hue.
  80275. */
  80276. get: function () {
  80277. return this._globalDensity;
  80278. },
  80279. /**
  80280. * Sets the global Density value.
  80281. * 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.
  80282. * Values less than zero provide a filter of opposite hue.
  80283. */
  80284. set: function (value) {
  80285. this._globalDensity = value;
  80286. this._dirty = true;
  80287. },
  80288. enumerable: true,
  80289. configurable: true
  80290. });
  80291. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  80292. /**
  80293. * Gets the global Saturation value.
  80294. * 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.
  80295. */
  80296. get: function () {
  80297. return this._globalSaturation;
  80298. },
  80299. /**
  80300. * Sets the global Saturation value.
  80301. * 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.
  80302. */
  80303. set: function (value) {
  80304. this._globalSaturation = value;
  80305. this._dirty = true;
  80306. },
  80307. enumerable: true,
  80308. configurable: true
  80309. });
  80310. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  80311. /**
  80312. * Gets the global Exposure value.
  80313. * 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.
  80314. */
  80315. get: function () {
  80316. return this._globalExposure;
  80317. },
  80318. /**
  80319. * Sets the global Exposure value.
  80320. * 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.
  80321. */
  80322. set: function (value) {
  80323. this._globalExposure = value;
  80324. this._dirty = true;
  80325. },
  80326. enumerable: true,
  80327. configurable: true
  80328. });
  80329. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  80330. /**
  80331. * Gets the highlights Hue value.
  80332. * 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).
  80333. */
  80334. get: function () {
  80335. return this._highlightsHue;
  80336. },
  80337. /**
  80338. * Sets the highlights Hue value.
  80339. * 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).
  80340. */
  80341. set: function (value) {
  80342. this._highlightsHue = value;
  80343. this._dirty = true;
  80344. },
  80345. enumerable: true,
  80346. configurable: true
  80347. });
  80348. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  80349. /**
  80350. * Gets the highlights Density value.
  80351. * 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.
  80352. * Values less than zero provide a filter of opposite hue.
  80353. */
  80354. get: function () {
  80355. return this._highlightsDensity;
  80356. },
  80357. /**
  80358. * Sets the highlights Density value.
  80359. * 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.
  80360. * Values less than zero provide a filter of opposite hue.
  80361. */
  80362. set: function (value) {
  80363. this._highlightsDensity = value;
  80364. this._dirty = true;
  80365. },
  80366. enumerable: true,
  80367. configurable: true
  80368. });
  80369. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  80370. /**
  80371. * Gets the highlights Saturation value.
  80372. * 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.
  80373. */
  80374. get: function () {
  80375. return this._highlightsSaturation;
  80376. },
  80377. /**
  80378. * Sets the highlights Saturation value.
  80379. * 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.
  80380. */
  80381. set: function (value) {
  80382. this._highlightsSaturation = value;
  80383. this._dirty = true;
  80384. },
  80385. enumerable: true,
  80386. configurable: true
  80387. });
  80388. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  80389. /**
  80390. * Gets the highlights Exposure value.
  80391. * 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.
  80392. */
  80393. get: function () {
  80394. return this._highlightsExposure;
  80395. },
  80396. /**
  80397. * Sets the highlights Exposure value.
  80398. * 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.
  80399. */
  80400. set: function (value) {
  80401. this._highlightsExposure = value;
  80402. this._dirty = true;
  80403. },
  80404. enumerable: true,
  80405. configurable: true
  80406. });
  80407. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  80408. /**
  80409. * Gets the midtones Hue value.
  80410. * 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).
  80411. */
  80412. get: function () {
  80413. return this._midtonesHue;
  80414. },
  80415. /**
  80416. * Sets the midtones Hue value.
  80417. * 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).
  80418. */
  80419. set: function (value) {
  80420. this._midtonesHue = value;
  80421. this._dirty = true;
  80422. },
  80423. enumerable: true,
  80424. configurable: true
  80425. });
  80426. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  80427. /**
  80428. * Gets the midtones Density value.
  80429. * 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.
  80430. * Values less than zero provide a filter of opposite hue.
  80431. */
  80432. get: function () {
  80433. return this._midtonesDensity;
  80434. },
  80435. /**
  80436. * Sets the midtones Density value.
  80437. * 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.
  80438. * Values less than zero provide a filter of opposite hue.
  80439. */
  80440. set: function (value) {
  80441. this._midtonesDensity = value;
  80442. this._dirty = true;
  80443. },
  80444. enumerable: true,
  80445. configurable: true
  80446. });
  80447. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  80448. /**
  80449. * Gets the midtones Saturation value.
  80450. * 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.
  80451. */
  80452. get: function () {
  80453. return this._midtonesSaturation;
  80454. },
  80455. /**
  80456. * Sets the midtones Saturation value.
  80457. * 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.
  80458. */
  80459. set: function (value) {
  80460. this._midtonesSaturation = value;
  80461. this._dirty = true;
  80462. },
  80463. enumerable: true,
  80464. configurable: true
  80465. });
  80466. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  80467. /**
  80468. * Gets the midtones Exposure value.
  80469. * 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.
  80470. */
  80471. get: function () {
  80472. return this._midtonesExposure;
  80473. },
  80474. /**
  80475. * Sets the midtones Exposure value.
  80476. * 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.
  80477. */
  80478. set: function (value) {
  80479. this._midtonesExposure = value;
  80480. this._dirty = true;
  80481. },
  80482. enumerable: true,
  80483. configurable: true
  80484. });
  80485. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  80486. /**
  80487. * Gets the shadows Hue value.
  80488. * 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).
  80489. */
  80490. get: function () {
  80491. return this._shadowsHue;
  80492. },
  80493. /**
  80494. * Sets the shadows Hue value.
  80495. * 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).
  80496. */
  80497. set: function (value) {
  80498. this._shadowsHue = value;
  80499. this._dirty = true;
  80500. },
  80501. enumerable: true,
  80502. configurable: true
  80503. });
  80504. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  80505. /**
  80506. * Gets the shadows Density value.
  80507. * 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.
  80508. * Values less than zero provide a filter of opposite hue.
  80509. */
  80510. get: function () {
  80511. return this._shadowsDensity;
  80512. },
  80513. /**
  80514. * Sets the shadows Density value.
  80515. * 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.
  80516. * Values less than zero provide a filter of opposite hue.
  80517. */
  80518. set: function (value) {
  80519. this._shadowsDensity = value;
  80520. this._dirty = true;
  80521. },
  80522. enumerable: true,
  80523. configurable: true
  80524. });
  80525. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  80526. /**
  80527. * Gets the shadows Saturation value.
  80528. * 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.
  80529. */
  80530. get: function () {
  80531. return this._shadowsSaturation;
  80532. },
  80533. /**
  80534. * Sets the shadows Saturation value.
  80535. * 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.
  80536. */
  80537. set: function (value) {
  80538. this._shadowsSaturation = value;
  80539. this._dirty = true;
  80540. },
  80541. enumerable: true,
  80542. configurable: true
  80543. });
  80544. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  80545. /**
  80546. * Gets the shadows Exposure value.
  80547. * 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.
  80548. */
  80549. get: function () {
  80550. return this._shadowsExposure;
  80551. },
  80552. /**
  80553. * Sets the shadows Exposure value.
  80554. * 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.
  80555. */
  80556. set: function (value) {
  80557. this._shadowsExposure = value;
  80558. this._dirty = true;
  80559. },
  80560. enumerable: true,
  80561. configurable: true
  80562. });
  80563. ColorCurves.prototype.getClassName = function () {
  80564. return "ColorCurves";
  80565. };
  80566. /**
  80567. * Binds the color curves to the shader.
  80568. * @param colorCurves The color curve to bind
  80569. * @param effect The effect to bind to
  80570. */
  80571. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  80572. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  80573. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  80574. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  80575. if (colorCurves._dirty) {
  80576. colorCurves._dirty = false;
  80577. // Fill in global info.
  80578. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  80579. // Compute highlights info.
  80580. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  80581. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  80582. // Compute midtones info.
  80583. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  80584. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  80585. // Compute shadows info.
  80586. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  80587. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  80588. // Compute deltas (neutral is midtones).
  80589. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  80590. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  80591. }
  80592. if (effect) {
  80593. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  80594. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  80595. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  80596. }
  80597. };
  80598. /**
  80599. * Prepare the list of uniforms associated with the ColorCurves effects.
  80600. * @param uniformsList The list of uniforms used in the effect
  80601. */
  80602. ColorCurves.PrepareUniforms = function (uniformsList) {
  80603. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  80604. };
  80605. /**
  80606. * Returns color grading data based on a hue, density, saturation and exposure value.
  80607. * @param filterHue The hue of the color filter.
  80608. * @param filterDensity The density of the color filter.
  80609. * @param saturation The saturation.
  80610. * @param exposure The exposure.
  80611. * @param result The result data container.
  80612. */
  80613. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  80614. if (hue == null) {
  80615. return;
  80616. }
  80617. hue = ColorCurves.clamp(hue, 0, 360);
  80618. density = ColorCurves.clamp(density, -100, 100);
  80619. saturation = ColorCurves.clamp(saturation, -100, 100);
  80620. exposure = ColorCurves.clamp(exposure, -100, 100);
  80621. // Remap the slider/config filter density with non-linear mapping and also scale by half
  80622. // so that the maximum filter density is only 50% control. This provides fine control
  80623. // for small values and reasonable range.
  80624. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  80625. density *= 0.5;
  80626. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  80627. if (density < 0) {
  80628. density *= -1;
  80629. hue = (hue + 180) % 360;
  80630. }
  80631. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  80632. result.scaleToRef(2, result);
  80633. result.a = 1 + 0.01 * saturation;
  80634. };
  80635. /**
  80636. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  80637. * @param value The input slider value in range [-100,100].
  80638. * @returns Adjusted value.
  80639. */
  80640. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  80641. value /= 100;
  80642. var x = Math.abs(value);
  80643. x = Math.pow(x, 2);
  80644. if (value < 0) {
  80645. x *= -1;
  80646. }
  80647. x *= 100;
  80648. return x;
  80649. };
  80650. /**
  80651. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  80652. * @param hue The hue (H) input.
  80653. * @param saturation The saturation (S) input.
  80654. * @param brightness The brightness (B) input.
  80655. * @result An RGBA color represented as Vector4.
  80656. */
  80657. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  80658. var h = ColorCurves.clamp(hue, 0, 360);
  80659. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  80660. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  80661. if (s === 0) {
  80662. result.r = v;
  80663. result.g = v;
  80664. result.b = v;
  80665. }
  80666. else {
  80667. // sector 0 to 5
  80668. h /= 60;
  80669. var i = Math.floor(h);
  80670. // fractional part of h
  80671. var f = h - i;
  80672. var p = v * (1 - s);
  80673. var q = v * (1 - s * f);
  80674. var t = v * (1 - s * (1 - f));
  80675. switch (i) {
  80676. case 0:
  80677. result.r = v;
  80678. result.g = t;
  80679. result.b = p;
  80680. break;
  80681. case 1:
  80682. result.r = q;
  80683. result.g = v;
  80684. result.b = p;
  80685. break;
  80686. case 2:
  80687. result.r = p;
  80688. result.g = v;
  80689. result.b = t;
  80690. break;
  80691. case 3:
  80692. result.r = p;
  80693. result.g = q;
  80694. result.b = v;
  80695. break;
  80696. case 4:
  80697. result.r = t;
  80698. result.g = p;
  80699. result.b = v;
  80700. break;
  80701. default: // case 5:
  80702. result.r = v;
  80703. result.g = p;
  80704. result.b = q;
  80705. break;
  80706. }
  80707. }
  80708. result.a = 1;
  80709. };
  80710. /**
  80711. * Returns a value clamped between min and max
  80712. * @param value The value to clamp
  80713. * @param min The minimum of value
  80714. * @param max The maximum of value
  80715. * @returns The clamped value.
  80716. */
  80717. ColorCurves.clamp = function (value, min, max) {
  80718. return Math.min(Math.max(value, min), max);
  80719. };
  80720. /**
  80721. * Clones the current color curve instance.
  80722. * @return The cloned curves
  80723. */
  80724. ColorCurves.prototype.clone = function () {
  80725. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  80726. };
  80727. /**
  80728. * Serializes the current color curve instance to a json representation.
  80729. * @return a JSON representation
  80730. */
  80731. ColorCurves.prototype.serialize = function () {
  80732. return BABYLON.SerializationHelper.Serialize(this);
  80733. };
  80734. /**
  80735. * Parses the color curve from a json representation.
  80736. * @param source the JSON source to parse
  80737. * @return The parsed curves
  80738. */
  80739. ColorCurves.Parse = function (source) {
  80740. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  80741. };
  80742. __decorate([
  80743. BABYLON.serialize()
  80744. ], ColorCurves.prototype, "_globalHue", void 0);
  80745. __decorate([
  80746. BABYLON.serialize()
  80747. ], ColorCurves.prototype, "_globalDensity", void 0);
  80748. __decorate([
  80749. BABYLON.serialize()
  80750. ], ColorCurves.prototype, "_globalSaturation", void 0);
  80751. __decorate([
  80752. BABYLON.serialize()
  80753. ], ColorCurves.prototype, "_globalExposure", void 0);
  80754. __decorate([
  80755. BABYLON.serialize()
  80756. ], ColorCurves.prototype, "_highlightsHue", void 0);
  80757. __decorate([
  80758. BABYLON.serialize()
  80759. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  80760. __decorate([
  80761. BABYLON.serialize()
  80762. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  80763. __decorate([
  80764. BABYLON.serialize()
  80765. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  80766. __decorate([
  80767. BABYLON.serialize()
  80768. ], ColorCurves.prototype, "_midtonesHue", void 0);
  80769. __decorate([
  80770. BABYLON.serialize()
  80771. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  80772. __decorate([
  80773. BABYLON.serialize()
  80774. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  80775. __decorate([
  80776. BABYLON.serialize()
  80777. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  80778. return ColorCurves;
  80779. }());
  80780. BABYLON.ColorCurves = ColorCurves;
  80781. })(BABYLON || (BABYLON = {}));
  80782. //# sourceMappingURL=babylon.colorCurves.js.map
  80783. var BABYLON;
  80784. (function (BABYLON) {
  80785. var RefractionPostProcess = /** @class */ (function (_super) {
  80786. __extends(RefractionPostProcess, _super);
  80787. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  80788. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  80789. _this.color = color;
  80790. _this.depth = depth;
  80791. _this.colorLevel = colorLevel;
  80792. _this._ownRefractionTexture = true;
  80793. _this.onActivateObservable.add(function (cam) {
  80794. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  80795. });
  80796. _this.onApplyObservable.add(function (effect) {
  80797. effect.setColor3("baseColor", _this.color);
  80798. effect.setFloat("depth", _this.depth);
  80799. effect.setFloat("colorLevel", _this.colorLevel);
  80800. effect.setTexture("refractionSampler", _this._refTexture);
  80801. });
  80802. return _this;
  80803. }
  80804. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  80805. /**
  80806. * Gets or sets the refraction texture
  80807. * Please note that you are responsible for disposing the texture if you set it manually
  80808. */
  80809. get: function () {
  80810. return this._refTexture;
  80811. },
  80812. set: function (value) {
  80813. if (this._refTexture && this._ownRefractionTexture) {
  80814. this._refTexture.dispose();
  80815. }
  80816. this._refTexture = value;
  80817. this._ownRefractionTexture = false;
  80818. },
  80819. enumerable: true,
  80820. configurable: true
  80821. });
  80822. // Methods
  80823. RefractionPostProcess.prototype.dispose = function (camera) {
  80824. if (this._refTexture && this._ownRefractionTexture) {
  80825. this._refTexture.dispose();
  80826. this._refTexture = null;
  80827. }
  80828. _super.prototype.dispose.call(this, camera);
  80829. };
  80830. return RefractionPostProcess;
  80831. }(BABYLON.PostProcess));
  80832. BABYLON.RefractionPostProcess = RefractionPostProcess;
  80833. })(BABYLON || (BABYLON = {}));
  80834. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  80835. var BABYLON;
  80836. (function (BABYLON) {
  80837. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  80838. __extends(BlackAndWhitePostProcess, _super);
  80839. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  80840. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  80841. _this.degree = 1;
  80842. _this.onApplyObservable.add(function (effect) {
  80843. effect.setFloat("degree", _this.degree);
  80844. });
  80845. return _this;
  80846. }
  80847. return BlackAndWhitePostProcess;
  80848. }(BABYLON.PostProcess));
  80849. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  80850. })(BABYLON || (BABYLON = {}));
  80851. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  80852. var BABYLON;
  80853. (function (BABYLON) {
  80854. /**
  80855. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  80856. * input texture to perform effects such as edge detection or sharpening
  80857. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80858. */
  80859. var ConvolutionPostProcess = /** @class */ (function (_super) {
  80860. __extends(ConvolutionPostProcess, _super);
  80861. /**
  80862. * Creates a new instance ConvolutionPostProcess
  80863. * @param name The name of the effect.
  80864. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  80865. * @param options The required width/height ratio to downsize to before computing the render pass.
  80866. * @param camera The camera to apply the render pass to.
  80867. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80868. * @param engine The engine which the post process will be applied. (default: current engine)
  80869. * @param reusable If the post process can be reused on the same frame. (default: false)
  80870. * @param textureType Type of textures used when performing the post process. (default: 0)
  80871. */
  80872. function ConvolutionPostProcess(name,
  80873. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  80874. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  80875. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80876. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80877. _this.kernel = kernel;
  80878. _this.onApply = function (effect) {
  80879. effect.setFloat2("screenSize", _this.width, _this.height);
  80880. effect.setArray("kernel", _this.kernel);
  80881. };
  80882. return _this;
  80883. }
  80884. // Statics
  80885. /**
  80886. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80887. */
  80888. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  80889. /**
  80890. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80891. */
  80892. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  80893. /**
  80894. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80895. */
  80896. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  80897. /**
  80898. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80899. */
  80900. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  80901. /**
  80902. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80903. */
  80904. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  80905. /**
  80906. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  80907. */
  80908. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  80909. return ConvolutionPostProcess;
  80910. }(BABYLON.PostProcess));
  80911. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  80912. })(BABYLON || (BABYLON = {}));
  80913. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  80914. var BABYLON;
  80915. (function (BABYLON) {
  80916. var FilterPostProcess = /** @class */ (function (_super) {
  80917. __extends(FilterPostProcess, _super);
  80918. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  80919. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  80920. _this.kernelMatrix = kernelMatrix;
  80921. _this.onApply = function (effect) {
  80922. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  80923. };
  80924. return _this;
  80925. }
  80926. return FilterPostProcess;
  80927. }(BABYLON.PostProcess));
  80928. BABYLON.FilterPostProcess = FilterPostProcess;
  80929. })(BABYLON || (BABYLON = {}));
  80930. //# sourceMappingURL=babylon.filterPostProcess.js.map
  80931. var BABYLON;
  80932. (function (BABYLON) {
  80933. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  80934. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  80935. __extends(VolumetricLightScatteringPostProcess, _super);
  80936. /**
  80937. * @constructor
  80938. * @param {string} name - The post-process name
  80939. * @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)
  80940. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  80941. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  80942. * @param {number} samples - The post-process quality, default 100
  80943. * @param {number} samplingMode - The post-process filtering mode
  80944. * @param {BABYLON.Engine} engine - The babylon engine
  80945. * @param {boolean} reusable - If the post-process is reusable
  80946. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  80947. */
  80948. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  80949. if (samples === void 0) { samples = 100; }
  80950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80951. 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;
  80952. _this._screenCoordinates = BABYLON.Vector2.Zero();
  80953. /**
  80954. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  80955. */
  80956. _this.customMeshPosition = BABYLON.Vector3.Zero();
  80957. /**
  80958. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  80959. */
  80960. _this.useCustomMeshPosition = false;
  80961. /**
  80962. * If the post-process should inverse the light scattering direction
  80963. */
  80964. _this.invert = true;
  80965. /**
  80966. * Array containing the excluded meshes not rendered in the internal pass
  80967. */
  80968. _this.excludedMeshes = new Array();
  80969. /**
  80970. * Controls the overall intensity of the post-process
  80971. */
  80972. _this.exposure = 0.3;
  80973. /**
  80974. * Dissipates each sample's contribution in range [0, 1]
  80975. */
  80976. _this.decay = 0.96815;
  80977. /**
  80978. * Controls the overall intensity of each sample
  80979. */
  80980. _this.weight = 0.58767;
  80981. /**
  80982. * Controls the density of each sample
  80983. */
  80984. _this.density = 0.926;
  80985. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  80986. engine = scene.getEngine();
  80987. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  80988. // Configure mesh
  80989. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  80990. // Configure
  80991. _this._createPass(scene, ratio.passRatio || ratio);
  80992. _this.onActivate = function (camera) {
  80993. if (!_this.isSupported) {
  80994. _this.dispose(camera);
  80995. }
  80996. _this.onActivate = null;
  80997. };
  80998. _this.onApplyObservable.add(function (effect) {
  80999. _this._updateMeshScreenCoordinates(scene);
  81000. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  81001. effect.setFloat("exposure", _this.exposure);
  81002. effect.setFloat("decay", _this.decay);
  81003. effect.setFloat("weight", _this.weight);
  81004. effect.setFloat("density", _this.density);
  81005. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  81006. });
  81007. return _this;
  81008. }
  81009. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  81010. get: function () {
  81011. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81012. return false;
  81013. },
  81014. set: function (useDiffuseColor) {
  81015. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81016. },
  81017. enumerable: true,
  81018. configurable: true
  81019. });
  81020. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  81021. return "VolumetricLightScatteringPostProcess";
  81022. };
  81023. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  81024. var mesh = subMesh.getMesh();
  81025. // Render this.mesh as default
  81026. if (mesh === this.mesh && mesh.material) {
  81027. return mesh.material.isReady(mesh);
  81028. }
  81029. var defines = [];
  81030. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81031. var material = subMesh.getMaterial();
  81032. // Alpha test
  81033. if (material) {
  81034. if (material.needAlphaTesting()) {
  81035. defines.push("#define ALPHATEST");
  81036. }
  81037. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81038. attribs.push(BABYLON.VertexBuffer.UVKind);
  81039. defines.push("#define UV1");
  81040. }
  81041. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81042. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81043. defines.push("#define UV2");
  81044. }
  81045. }
  81046. // Bones
  81047. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81048. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81049. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81050. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81051. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  81052. }
  81053. else {
  81054. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81055. }
  81056. // Instances
  81057. if (useInstances) {
  81058. defines.push("#define INSTANCES");
  81059. attribs.push("world0");
  81060. attribs.push("world1");
  81061. attribs.push("world2");
  81062. attribs.push("world3");
  81063. }
  81064. // Get correct effect
  81065. var join = defines.join("\n");
  81066. if (this._cachedDefines !== join) {
  81067. this._cachedDefines = join;
  81068. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  81069. }
  81070. return this._volumetricLightScatteringPass.isReady();
  81071. };
  81072. /**
  81073. * Sets the new light position for light scattering effect
  81074. * @param {BABYLON.Vector3} The new custom light position
  81075. */
  81076. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  81077. this.customMeshPosition = position;
  81078. };
  81079. /**
  81080. * Returns the light position for light scattering effect
  81081. * @return {BABYLON.Vector3} The custom light position
  81082. */
  81083. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  81084. return this.customMeshPosition;
  81085. };
  81086. /**
  81087. * Disposes the internal assets and detaches the post-process from the camera
  81088. */
  81089. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  81090. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  81091. if (rttIndex !== -1) {
  81092. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  81093. }
  81094. this._volumetricLightScatteringRTT.dispose();
  81095. _super.prototype.dispose.call(this, camera);
  81096. };
  81097. /**
  81098. * Returns the render target texture used by the post-process
  81099. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  81100. */
  81101. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  81102. return this._volumetricLightScatteringRTT;
  81103. };
  81104. // Private methods
  81105. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  81106. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  81107. return true;
  81108. }
  81109. return false;
  81110. };
  81111. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  81112. var _this = this;
  81113. var engine = scene.getEngine();
  81114. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81115. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81116. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81117. this._volumetricLightScatteringRTT.renderList = null;
  81118. this._volumetricLightScatteringRTT.renderParticles = false;
  81119. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  81120. var camera = this.getCamera();
  81121. if (camera) {
  81122. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81123. }
  81124. else {
  81125. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81126. }
  81127. // Custom render function for submeshes
  81128. var renderSubMesh = function (subMesh) {
  81129. var mesh = subMesh.getRenderingMesh();
  81130. if (_this._meshExcluded(mesh)) {
  81131. return;
  81132. }
  81133. var material = subMesh.getMaterial();
  81134. if (!material) {
  81135. return;
  81136. }
  81137. var scene = mesh.getScene();
  81138. var engine = scene.getEngine();
  81139. // Culling
  81140. engine.setState(material.backFaceCulling);
  81141. // Managing instances
  81142. var batch = mesh._getInstancesRenderList(subMesh._id);
  81143. if (batch.mustReturn) {
  81144. return;
  81145. }
  81146. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81147. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  81148. var effect = _this._volumetricLightScatteringPass;
  81149. if (mesh === _this.mesh) {
  81150. if (subMesh.effect) {
  81151. effect = subMesh.effect;
  81152. }
  81153. else {
  81154. effect = material.getEffect();
  81155. }
  81156. }
  81157. engine.enableEffect(effect);
  81158. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  81159. if (mesh === _this.mesh) {
  81160. material.bind(mesh.getWorldMatrix(), mesh);
  81161. }
  81162. else {
  81163. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  81164. // Alpha test
  81165. if (material && material.needAlphaTesting()) {
  81166. var alphaTexture = material.getAlphaTestTexture();
  81167. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  81168. if (alphaTexture) {
  81169. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81170. }
  81171. }
  81172. // Bones
  81173. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81174. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81175. }
  81176. }
  81177. // Draw
  81178. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  81179. }
  81180. };
  81181. // Render target texture callbacks
  81182. var savedSceneClearColor;
  81183. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  81184. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  81185. savedSceneClearColor = scene.clearColor;
  81186. scene.clearColor = sceneClearColor;
  81187. });
  81188. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  81189. scene.clearColor = savedSceneClearColor;
  81190. });
  81191. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81192. var engine = scene.getEngine();
  81193. var index;
  81194. if (depthOnlySubMeshes.length) {
  81195. engine.setColorWrite(false);
  81196. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81197. renderSubMesh(depthOnlySubMeshes.data[index]);
  81198. }
  81199. engine.setColorWrite(true);
  81200. }
  81201. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81202. renderSubMesh(opaqueSubMeshes.data[index]);
  81203. }
  81204. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  81205. renderSubMesh(alphaTestSubMeshes.data[index]);
  81206. }
  81207. if (transparentSubMeshes.length) {
  81208. // Sort sub meshes
  81209. for (index = 0; index < transparentSubMeshes.length; index++) {
  81210. var submesh = transparentSubMeshes.data[index];
  81211. var boundingInfo = submesh.getBoundingInfo();
  81212. if (boundingInfo && scene.activeCamera) {
  81213. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  81214. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  81215. }
  81216. }
  81217. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  81218. sortedArray.sort(function (a, b) {
  81219. // Alpha index first
  81220. if (a._alphaIndex > b._alphaIndex) {
  81221. return 1;
  81222. }
  81223. if (a._alphaIndex < b._alphaIndex) {
  81224. return -1;
  81225. }
  81226. // Then distance to camera
  81227. if (a._distanceToCamera < b._distanceToCamera) {
  81228. return 1;
  81229. }
  81230. if (a._distanceToCamera > b._distanceToCamera) {
  81231. return -1;
  81232. }
  81233. return 0;
  81234. });
  81235. // Render sub meshes
  81236. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  81237. for (index = 0; index < sortedArray.length; index++) {
  81238. renderSubMesh(sortedArray[index]);
  81239. }
  81240. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81241. }
  81242. };
  81243. };
  81244. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  81245. var transform = scene.getTransformMatrix();
  81246. var meshPosition;
  81247. if (this.useCustomMeshPosition) {
  81248. meshPosition = this.customMeshPosition;
  81249. }
  81250. else if (this.attachedNode) {
  81251. meshPosition = this.attachedNode.position;
  81252. }
  81253. else {
  81254. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  81255. }
  81256. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  81257. this._screenCoordinates.x = pos.x / this._viewPort.width;
  81258. this._screenCoordinates.y = pos.y / this._viewPort.height;
  81259. if (this.invert)
  81260. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  81261. };
  81262. // Static methods
  81263. /**
  81264. * Creates a default mesh for the Volumeric Light Scattering post-process
  81265. * @param {string} The mesh name
  81266. * @param {BABYLON.Scene} The scene where to create the mesh
  81267. * @return {BABYLON.Mesh} the default mesh
  81268. */
  81269. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  81270. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  81271. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  81272. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  81273. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  81274. mesh.material = material;
  81275. return mesh;
  81276. };
  81277. __decorate([
  81278. BABYLON.serializeAsVector3()
  81279. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  81280. __decorate([
  81281. BABYLON.serialize()
  81282. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  81283. __decorate([
  81284. BABYLON.serialize()
  81285. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  81286. __decorate([
  81287. BABYLON.serializeAsMeshReference()
  81288. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  81289. __decorate([
  81290. BABYLON.serialize()
  81291. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  81292. __decorate([
  81293. BABYLON.serialize()
  81294. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  81295. __decorate([
  81296. BABYLON.serialize()
  81297. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  81298. __decorate([
  81299. BABYLON.serialize()
  81300. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  81301. __decorate([
  81302. BABYLON.serialize()
  81303. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  81304. return VolumetricLightScatteringPostProcess;
  81305. }(BABYLON.PostProcess));
  81306. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  81307. })(BABYLON || (BABYLON = {}));
  81308. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  81309. //
  81310. // This post-process allows the modification of rendered colors by using
  81311. // a 'look-up table' (LUT). This effect is also called Color Grading.
  81312. //
  81313. // The object needs to be provided an url to a texture containing the color
  81314. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  81315. // Use an image editing software to tweak the LUT to match your needs.
  81316. //
  81317. // For an example of a color LUT, see here:
  81318. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  81319. // For explanations on color grading, see here:
  81320. // http://udn.epicgames.com/Three/ColorGrading.html
  81321. //
  81322. var BABYLON;
  81323. (function (BABYLON) {
  81324. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  81325. __extends(ColorCorrectionPostProcess, _super);
  81326. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  81327. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  81328. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81329. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  81330. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81331. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81332. _this.onApply = function (effect) {
  81333. effect.setTexture("colorTable", _this._colorTableTexture);
  81334. };
  81335. return _this;
  81336. }
  81337. return ColorCorrectionPostProcess;
  81338. }(BABYLON.PostProcess));
  81339. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  81340. })(BABYLON || (BABYLON = {}));
  81341. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  81342. var BABYLON;
  81343. (function (BABYLON) {
  81344. /** Defines operator used for tonemapping */
  81345. var TonemappingOperator;
  81346. (function (TonemappingOperator) {
  81347. /** Hable */
  81348. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  81349. /** Reinhard */
  81350. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  81351. /** HejiDawson */
  81352. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  81353. /** Photographic */
  81354. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  81355. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  81356. ;
  81357. /**
  81358. * Defines a post process to apply tone mapping
  81359. */
  81360. var TonemapPostProcess = /** @class */ (function (_super) {
  81361. __extends(TonemapPostProcess, _super);
  81362. /**
  81363. * Creates a new TonemapPostProcess
  81364. * @param name defines the name of the postprocess
  81365. * @param _operator defines the operator to use
  81366. * @param exposureAdjustment defines the required exposure adjustement
  81367. * @param camera defines the camera to use (can be null)
  81368. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  81369. * @param engine defines the hosting engine (can be ignore if camera is set)
  81370. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  81371. */
  81372. function TonemapPostProcess(name, _operator,
  81373. /** Defines the required exposure adjustement */
  81374. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  81375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81376. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81377. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  81378. _this._operator = _operator;
  81379. _this.exposureAdjustment = exposureAdjustment;
  81380. var defines = "#define ";
  81381. if (_this._operator === TonemappingOperator.Hable)
  81382. defines += "HABLE_TONEMAPPING";
  81383. else if (_this._operator === TonemappingOperator.Reinhard)
  81384. defines += "REINHARD_TONEMAPPING";
  81385. else if (_this._operator === TonemappingOperator.HejiDawson)
  81386. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  81387. else if (_this._operator === TonemappingOperator.Photographic)
  81388. defines += "PHOTOGRAPHIC_TONEMAPPING";
  81389. //sadly a second call to create the effect.
  81390. _this.updateEffect(defines);
  81391. _this.onApply = function (effect) {
  81392. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  81393. };
  81394. return _this;
  81395. }
  81396. return TonemapPostProcess;
  81397. }(BABYLON.PostProcess));
  81398. BABYLON.TonemapPostProcess = TonemapPostProcess;
  81399. })(BABYLON || (BABYLON = {}));
  81400. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  81401. var BABYLON;
  81402. (function (BABYLON) {
  81403. var DisplayPassPostProcess = /** @class */ (function (_super) {
  81404. __extends(DisplayPassPostProcess, _super);
  81405. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  81406. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  81407. }
  81408. return DisplayPassPostProcess;
  81409. }(BABYLON.PostProcess));
  81410. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  81411. })(BABYLON || (BABYLON = {}));
  81412. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  81413. var BABYLON;
  81414. (function (BABYLON) {
  81415. var HighlightsPostProcess = /** @class */ (function (_super) {
  81416. __extends(HighlightsPostProcess, _super);
  81417. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  81418. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81419. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81420. }
  81421. return HighlightsPostProcess;
  81422. }(BABYLON.PostProcess));
  81423. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  81424. })(BABYLON || (BABYLON = {}));
  81425. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  81426. var BABYLON;
  81427. (function (BABYLON) {
  81428. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  81429. __extends(ImageProcessingPostProcess, _super);
  81430. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  81431. if (camera === void 0) { camera = null; }
  81432. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81433. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  81434. _this._fromLinearSpace = true;
  81435. /**
  81436. * Defines cache preventing GC.
  81437. */
  81438. _this._defines = {
  81439. IMAGEPROCESSING: false,
  81440. VIGNETTE: false,
  81441. VIGNETTEBLENDMODEMULTIPLY: false,
  81442. VIGNETTEBLENDMODEOPAQUE: false,
  81443. TONEMAPPING: false,
  81444. TONEMAPPING_ACES: false,
  81445. CONTRAST: false,
  81446. COLORCURVES: false,
  81447. COLORGRADING: false,
  81448. COLORGRADING3D: false,
  81449. FROMLINEARSPACE: false,
  81450. SAMPLER3DGREENDEPTH: false,
  81451. SAMPLER3DBGRMAP: false,
  81452. IMAGEPROCESSINGPOSTPROCESS: false,
  81453. EXPOSURE: false,
  81454. };
  81455. // Setup the configuration as forced by the constructor. This would then not force the
  81456. // scene materials output in linear space and let untouched the default forward pass.
  81457. if (imageProcessingConfiguration) {
  81458. imageProcessingConfiguration.applyByPostProcess = true;
  81459. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  81460. // This will cause the shader to be compiled
  81461. _this.fromLinearSpace = false;
  81462. }
  81463. // Setup the default processing configuration to the scene.
  81464. else {
  81465. _this._attachImageProcessingConfiguration(null, true);
  81466. _this.imageProcessingConfiguration.applyByPostProcess = true;
  81467. }
  81468. _this.onApply = function (effect) {
  81469. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  81470. };
  81471. return _this;
  81472. }
  81473. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  81474. /**
  81475. * Gets the image processing configuration used either in this material.
  81476. */
  81477. get: function () {
  81478. return this._imageProcessingConfiguration;
  81479. },
  81480. /**
  81481. * Sets the Default image processing configuration used either in the this material.
  81482. *
  81483. * If sets to null, the scene one is in use.
  81484. */
  81485. set: function (value) {
  81486. this._attachImageProcessingConfiguration(value);
  81487. },
  81488. enumerable: true,
  81489. configurable: true
  81490. });
  81491. /**
  81492. * Attaches a new image processing configuration to the PBR Material.
  81493. * @param configuration
  81494. */
  81495. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  81496. var _this = this;
  81497. if (doNotBuild === void 0) { doNotBuild = false; }
  81498. if (configuration === this._imageProcessingConfiguration) {
  81499. return;
  81500. }
  81501. // Detaches observer.
  81502. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81503. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81504. }
  81505. // Pick the scene configuration if needed.
  81506. if (!configuration) {
  81507. var scene = null;
  81508. var engine = this.getEngine();
  81509. var camera = this.getCamera();
  81510. if (camera) {
  81511. scene = camera.getScene();
  81512. }
  81513. else if (engine && engine.scenes) {
  81514. var scenes = engine.scenes;
  81515. scene = scenes[scenes.length - 1];
  81516. }
  81517. else {
  81518. scene = BABYLON.Engine.LastCreatedScene;
  81519. }
  81520. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  81521. }
  81522. else {
  81523. this._imageProcessingConfiguration = configuration;
  81524. }
  81525. // Attaches observer.
  81526. if (this._imageProcessingConfiguration) {
  81527. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  81528. _this._updateParameters();
  81529. });
  81530. }
  81531. // Ensure the effect will be rebuilt.
  81532. if (!doNotBuild) {
  81533. this._updateParameters();
  81534. }
  81535. };
  81536. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  81537. /**
  81538. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  81539. */
  81540. get: function () {
  81541. return this.imageProcessingConfiguration.colorCurves;
  81542. },
  81543. /**
  81544. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  81545. */
  81546. set: function (value) {
  81547. this.imageProcessingConfiguration.colorCurves = value;
  81548. },
  81549. enumerable: true,
  81550. configurable: true
  81551. });
  81552. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  81553. /**
  81554. * Gets wether the color curves effect is enabled.
  81555. */
  81556. get: function () {
  81557. return this.imageProcessingConfiguration.colorCurvesEnabled;
  81558. },
  81559. /**
  81560. * Sets wether the color curves effect is enabled.
  81561. */
  81562. set: function (value) {
  81563. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  81564. },
  81565. enumerable: true,
  81566. configurable: true
  81567. });
  81568. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  81569. /**
  81570. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  81571. */
  81572. get: function () {
  81573. return this.imageProcessingConfiguration.colorGradingTexture;
  81574. },
  81575. /**
  81576. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  81577. */
  81578. set: function (value) {
  81579. this.imageProcessingConfiguration.colorGradingTexture = value;
  81580. },
  81581. enumerable: true,
  81582. configurable: true
  81583. });
  81584. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  81585. /**
  81586. * Gets wether the color grading effect is enabled.
  81587. */
  81588. get: function () {
  81589. return this.imageProcessingConfiguration.colorGradingEnabled;
  81590. },
  81591. /**
  81592. * Gets wether the color grading effect is enabled.
  81593. */
  81594. set: function (value) {
  81595. this.imageProcessingConfiguration.colorGradingEnabled = value;
  81596. },
  81597. enumerable: true,
  81598. configurable: true
  81599. });
  81600. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  81601. /**
  81602. * Gets exposure used in the effect.
  81603. */
  81604. get: function () {
  81605. return this.imageProcessingConfiguration.exposure;
  81606. },
  81607. /**
  81608. * Sets exposure used in the effect.
  81609. */
  81610. set: function (value) {
  81611. this.imageProcessingConfiguration.exposure = value;
  81612. },
  81613. enumerable: true,
  81614. configurable: true
  81615. });
  81616. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  81617. /**
  81618. * Gets wether tonemapping is enabled or not.
  81619. */
  81620. get: function () {
  81621. return this._imageProcessingConfiguration.toneMappingEnabled;
  81622. },
  81623. /**
  81624. * Sets wether tonemapping is enabled or not
  81625. */
  81626. set: function (value) {
  81627. this._imageProcessingConfiguration.toneMappingEnabled = value;
  81628. },
  81629. enumerable: true,
  81630. configurable: true
  81631. });
  81632. ;
  81633. ;
  81634. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  81635. /**
  81636. * Gets contrast used in the effect.
  81637. */
  81638. get: function () {
  81639. return this.imageProcessingConfiguration.contrast;
  81640. },
  81641. /**
  81642. * Sets contrast used in the effect.
  81643. */
  81644. set: function (value) {
  81645. this.imageProcessingConfiguration.contrast = value;
  81646. },
  81647. enumerable: true,
  81648. configurable: true
  81649. });
  81650. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  81651. /**
  81652. * Gets Vignette stretch size.
  81653. */
  81654. get: function () {
  81655. return this.imageProcessingConfiguration.vignetteStretch;
  81656. },
  81657. /**
  81658. * Sets Vignette stretch size.
  81659. */
  81660. set: function (value) {
  81661. this.imageProcessingConfiguration.vignetteStretch = value;
  81662. },
  81663. enumerable: true,
  81664. configurable: true
  81665. });
  81666. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  81667. /**
  81668. * Gets Vignette centre X Offset.
  81669. */
  81670. get: function () {
  81671. return this.imageProcessingConfiguration.vignetteCentreX;
  81672. },
  81673. /**
  81674. * Sets Vignette centre X Offset.
  81675. */
  81676. set: function (value) {
  81677. this.imageProcessingConfiguration.vignetteCentreX = value;
  81678. },
  81679. enumerable: true,
  81680. configurable: true
  81681. });
  81682. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  81683. /**
  81684. * Gets Vignette centre Y Offset.
  81685. */
  81686. get: function () {
  81687. return this.imageProcessingConfiguration.vignetteCentreY;
  81688. },
  81689. /**
  81690. * Sets Vignette centre Y Offset.
  81691. */
  81692. set: function (value) {
  81693. this.imageProcessingConfiguration.vignetteCentreY = value;
  81694. },
  81695. enumerable: true,
  81696. configurable: true
  81697. });
  81698. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  81699. /**
  81700. * Gets Vignette weight or intensity of the vignette effect.
  81701. */
  81702. get: function () {
  81703. return this.imageProcessingConfiguration.vignetteWeight;
  81704. },
  81705. /**
  81706. * Sets Vignette weight or intensity of the vignette effect.
  81707. */
  81708. set: function (value) {
  81709. this.imageProcessingConfiguration.vignetteWeight = value;
  81710. },
  81711. enumerable: true,
  81712. configurable: true
  81713. });
  81714. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  81715. /**
  81716. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81717. * if vignetteEnabled is set to true.
  81718. */
  81719. get: function () {
  81720. return this.imageProcessingConfiguration.vignetteColor;
  81721. },
  81722. /**
  81723. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81724. * if vignetteEnabled is set to true.
  81725. */
  81726. set: function (value) {
  81727. this.imageProcessingConfiguration.vignetteColor = value;
  81728. },
  81729. enumerable: true,
  81730. configurable: true
  81731. });
  81732. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  81733. /**
  81734. * Gets Camera field of view used by the Vignette effect.
  81735. */
  81736. get: function () {
  81737. return this.imageProcessingConfiguration.vignetteCameraFov;
  81738. },
  81739. /**
  81740. * Sets Camera field of view used by the Vignette effect.
  81741. */
  81742. set: function (value) {
  81743. this.imageProcessingConfiguration.vignetteCameraFov = value;
  81744. },
  81745. enumerable: true,
  81746. configurable: true
  81747. });
  81748. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  81749. /**
  81750. * Gets the vignette blend mode allowing different kind of effect.
  81751. */
  81752. get: function () {
  81753. return this.imageProcessingConfiguration.vignetteBlendMode;
  81754. },
  81755. /**
  81756. * Sets the vignette blend mode allowing different kind of effect.
  81757. */
  81758. set: function (value) {
  81759. this.imageProcessingConfiguration.vignetteBlendMode = value;
  81760. },
  81761. enumerable: true,
  81762. configurable: true
  81763. });
  81764. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  81765. /**
  81766. * Gets wether the vignette effect is enabled.
  81767. */
  81768. get: function () {
  81769. return this.imageProcessingConfiguration.vignetteEnabled;
  81770. },
  81771. /**
  81772. * Sets wether the vignette effect is enabled.
  81773. */
  81774. set: function (value) {
  81775. this.imageProcessingConfiguration.vignetteEnabled = value;
  81776. },
  81777. enumerable: true,
  81778. configurable: true
  81779. });
  81780. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  81781. /**
  81782. * Gets wether the input of the processing is in Gamma or Linear Space.
  81783. */
  81784. get: function () {
  81785. return this._fromLinearSpace;
  81786. },
  81787. /**
  81788. * Sets wether the input of the processing is in Gamma or Linear Space.
  81789. */
  81790. set: function (value) {
  81791. if (this._fromLinearSpace === value) {
  81792. return;
  81793. }
  81794. this._fromLinearSpace = value;
  81795. this._updateParameters();
  81796. },
  81797. enumerable: true,
  81798. configurable: true
  81799. });
  81800. ImageProcessingPostProcess.prototype.getClassName = function () {
  81801. return "ImageProcessingPostProcess";
  81802. };
  81803. ImageProcessingPostProcess.prototype._updateParameters = function () {
  81804. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  81805. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  81806. var defines = "";
  81807. for (var define in this._defines) {
  81808. if (this._defines[define]) {
  81809. defines += "#define " + define + ";\r\n";
  81810. }
  81811. }
  81812. var samplers = ["textureSampler"];
  81813. var uniforms = ["scale"];
  81814. if (BABYLON.ImageProcessingConfiguration) {
  81815. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  81816. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  81817. }
  81818. this.updateEffect(defines, uniforms, samplers);
  81819. };
  81820. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  81821. _super.prototype.dispose.call(this, camera);
  81822. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81823. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81824. }
  81825. if (this._imageProcessingConfiguration) {
  81826. this.imageProcessingConfiguration.applyByPostProcess = false;
  81827. }
  81828. };
  81829. __decorate([
  81830. BABYLON.serialize()
  81831. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  81832. return ImageProcessingPostProcess;
  81833. }(BABYLON.PostProcess));
  81834. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  81835. })(BABYLON || (BABYLON = {}));
  81836. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  81837. var BABYLON;
  81838. (function (BABYLON) {
  81839. /**
  81840. * Class used to store bone information
  81841. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81842. */
  81843. var Bone = /** @class */ (function (_super) {
  81844. __extends(Bone, _super);
  81845. /**
  81846. * Create a new bone
  81847. * @param name defines the bone name
  81848. * @param skeleton defines the parent skeleton
  81849. * @param parentBone defines the parent (can be null if the bone is the root)
  81850. * @param localMatrix defines the local matrix
  81851. * @param restPose defines the rest pose matrix
  81852. * @param baseMatrix defines the base matrix
  81853. * @param index defines index of the bone in the hiearchy
  81854. */
  81855. function Bone(
  81856. /**
  81857. * defines the bone name
  81858. */
  81859. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  81860. if (parentBone === void 0) { parentBone = null; }
  81861. if (localMatrix === void 0) { localMatrix = null; }
  81862. if (restPose === void 0) { restPose = null; }
  81863. if (baseMatrix === void 0) { baseMatrix = null; }
  81864. if (index === void 0) { index = null; }
  81865. var _this = _super.call(this, name, skeleton.getScene()) || this;
  81866. _this.name = name;
  81867. /**
  81868. * Gets the list of child bones
  81869. */
  81870. _this.children = new Array();
  81871. /** Gets the animations associated with this bone */
  81872. _this.animations = new Array();
  81873. /**
  81874. * @hidden Internal only
  81875. * Set this value to map this bone to a different index in the transform matrices
  81876. * Set this value to -1 to exclude the bone from the transform matrices
  81877. */
  81878. _this._index = null;
  81879. _this._absoluteTransform = new BABYLON.Matrix();
  81880. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  81881. _this._scalingDeterminant = 1;
  81882. _this._worldTransform = new BABYLON.Matrix();
  81883. _this._needToDecompose = true;
  81884. _this._needToCompose = false;
  81885. _this._skeleton = skeleton;
  81886. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  81887. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  81888. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  81889. _this._index = index;
  81890. skeleton.bones.push(_this);
  81891. _this.setParent(parentBone, false);
  81892. if (baseMatrix || localMatrix) {
  81893. _this._updateDifferenceMatrix();
  81894. }
  81895. return _this;
  81896. }
  81897. Object.defineProperty(Bone.prototype, "_matrix", {
  81898. /** @hidden */
  81899. get: function () {
  81900. this._compose();
  81901. return this._localMatrix;
  81902. },
  81903. /** @hidden */
  81904. set: function (value) {
  81905. this._localMatrix.copyFrom(value);
  81906. this._needToDecompose = true;
  81907. },
  81908. enumerable: true,
  81909. configurable: true
  81910. });
  81911. // Members
  81912. /**
  81913. * Gets the parent skeleton
  81914. * @returns a skeleton
  81915. */
  81916. Bone.prototype.getSkeleton = function () {
  81917. return this._skeleton;
  81918. };
  81919. /**
  81920. * Gets parent bone
  81921. * @returns a bone or null if the bone is the root of the bone hierarchy
  81922. */
  81923. Bone.prototype.getParent = function () {
  81924. return this._parent;
  81925. };
  81926. /**
  81927. * Sets the parent bone
  81928. * @param parent defines the parent (can be null if the bone is the root)
  81929. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  81930. */
  81931. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  81932. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  81933. if (this._parent === parent) {
  81934. return;
  81935. }
  81936. if (this._parent) {
  81937. var index = this._parent.children.indexOf(this);
  81938. if (index !== -1) {
  81939. this._parent.children.splice(index, 1);
  81940. }
  81941. }
  81942. this._parent = parent;
  81943. if (this._parent) {
  81944. this._parent.children.push(this);
  81945. }
  81946. if (updateDifferenceMatrix) {
  81947. this._updateDifferenceMatrix();
  81948. }
  81949. this.markAsDirty();
  81950. };
  81951. /**
  81952. * Gets the local matrix
  81953. * @returns a matrix
  81954. */
  81955. Bone.prototype.getLocalMatrix = function () {
  81956. this._compose();
  81957. return this._localMatrix;
  81958. };
  81959. /**
  81960. * Gets the base matrix (initial matrix which remains unchanged)
  81961. * @returns a matrix
  81962. */
  81963. Bone.prototype.getBaseMatrix = function () {
  81964. return this._baseMatrix;
  81965. };
  81966. /**
  81967. * Gets the rest pose matrix
  81968. * @returns a matrix
  81969. */
  81970. Bone.prototype.getRestPose = function () {
  81971. return this._restPose;
  81972. };
  81973. /**
  81974. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  81975. */
  81976. Bone.prototype.getWorldMatrix = function () {
  81977. return this._worldTransform;
  81978. };
  81979. /**
  81980. * Sets the local matrix to rest pose matrix
  81981. */
  81982. Bone.prototype.returnToRest = function () {
  81983. this.updateMatrix(this._restPose.clone());
  81984. };
  81985. /**
  81986. * Gets the inverse of the absolute transform matrix.
  81987. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  81988. * @returns a matrix
  81989. */
  81990. Bone.prototype.getInvertedAbsoluteTransform = function () {
  81991. return this._invertedAbsoluteTransform;
  81992. };
  81993. /**
  81994. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  81995. * @returns a matrix
  81996. */
  81997. Bone.prototype.getAbsoluteTransform = function () {
  81998. return this._absoluteTransform;
  81999. };
  82000. Object.defineProperty(Bone.prototype, "position", {
  82001. // Properties (matches AbstractMesh properties)
  82002. /** Gets or sets current position (in local space) */
  82003. get: function () {
  82004. this._decompose();
  82005. return this._localPosition;
  82006. },
  82007. set: function (newPosition) {
  82008. this._decompose();
  82009. this._localPosition.copyFrom(newPosition);
  82010. this._markAsDirtyAndCompose();
  82011. },
  82012. enumerable: true,
  82013. configurable: true
  82014. });
  82015. Object.defineProperty(Bone.prototype, "rotation", {
  82016. /** Gets or sets current rotation (in local space) */
  82017. get: function () {
  82018. return this.getRotation();
  82019. },
  82020. set: function (newRotation) {
  82021. this.setRotation(newRotation);
  82022. },
  82023. enumerable: true,
  82024. configurable: true
  82025. });
  82026. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  82027. /** Gets or sets current rotation quaternion (in local space) */
  82028. get: function () {
  82029. this._decompose();
  82030. return this._localRotation;
  82031. },
  82032. set: function (newRotation) {
  82033. this.setRotationQuaternion(newRotation);
  82034. },
  82035. enumerable: true,
  82036. configurable: true
  82037. });
  82038. Object.defineProperty(Bone.prototype, "scaling", {
  82039. /** Gets or sets current scaling (in local space) */
  82040. get: function () {
  82041. return this.getScale();
  82042. },
  82043. set: function (newScaling) {
  82044. this.setScale(newScaling);
  82045. },
  82046. enumerable: true,
  82047. configurable: true
  82048. });
  82049. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  82050. /**
  82051. * Gets the animation properties override
  82052. */
  82053. get: function () {
  82054. return this._skeleton.animationPropertiesOverride;
  82055. },
  82056. enumerable: true,
  82057. configurable: true
  82058. });
  82059. // Methods
  82060. Bone.prototype._decompose = function () {
  82061. if (!this._needToDecompose) {
  82062. return;
  82063. }
  82064. this._needToDecompose = false;
  82065. if (!this._localScaling) {
  82066. this._localScaling = BABYLON.Vector3.Zero();
  82067. this._localRotation = BABYLON.Quaternion.Zero();
  82068. this._localPosition = BABYLON.Vector3.Zero();
  82069. }
  82070. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  82071. };
  82072. Bone.prototype._compose = function () {
  82073. if (!this._needToCompose) {
  82074. return;
  82075. }
  82076. this._needToCompose = false;
  82077. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  82078. };
  82079. /**
  82080. * Update the base and local matrices
  82081. * @param matrix defines the new base or local matrix
  82082. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82083. * @param updateLocalMatrix defines if the local matrix should be updated
  82084. */
  82085. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  82086. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82087. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  82088. this._baseMatrix.copyFrom(matrix);
  82089. if (updateDifferenceMatrix) {
  82090. this._updateDifferenceMatrix();
  82091. }
  82092. if (updateLocalMatrix) {
  82093. this._localMatrix.copyFrom(matrix);
  82094. this._markAsDirtyAndDecompose();
  82095. }
  82096. else {
  82097. this.markAsDirty();
  82098. }
  82099. };
  82100. /** @hidden */
  82101. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  82102. if (updateChildren === void 0) { updateChildren = true; }
  82103. if (!rootMatrix) {
  82104. rootMatrix = this._baseMatrix;
  82105. }
  82106. if (this._parent) {
  82107. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82108. }
  82109. else {
  82110. this._absoluteTransform.copyFrom(rootMatrix);
  82111. }
  82112. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  82113. if (updateChildren) {
  82114. for (var index = 0; index < this.children.length; index++) {
  82115. this.children[index]._updateDifferenceMatrix();
  82116. }
  82117. }
  82118. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  82119. };
  82120. /**
  82121. * Flag the bone as dirty (Forcing it to update everything)
  82122. */
  82123. Bone.prototype.markAsDirty = function () {
  82124. this._currentRenderId++;
  82125. this._childRenderId++;
  82126. this._skeleton._markAsDirty();
  82127. };
  82128. Bone.prototype._markAsDirtyAndCompose = function () {
  82129. this.markAsDirty();
  82130. this._needToCompose = true;
  82131. };
  82132. Bone.prototype._markAsDirtyAndDecompose = function () {
  82133. this.markAsDirty();
  82134. this._needToDecompose = true;
  82135. };
  82136. /**
  82137. * Copy an animation range from another bone
  82138. * @param source defines the source bone
  82139. * @param rangeName defines the range name to copy
  82140. * @param frameOffset defines the frame offset
  82141. * @param rescaleAsRequired defines if rescaling must be applied if required
  82142. * @param skelDimensionsRatio defines the scaling ratio
  82143. * @returns true if operation was successful
  82144. */
  82145. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  82146. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82147. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  82148. // all animation may be coming from a library skeleton, so may need to create animation
  82149. if (this.animations.length === 0) {
  82150. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  82151. this.animations[0].setKeys([]);
  82152. }
  82153. // get animation info / verify there is such a range from the source bone
  82154. var sourceRange = source.animations[0].getRange(rangeName);
  82155. if (!sourceRange) {
  82156. return false;
  82157. }
  82158. var from = sourceRange.from;
  82159. var to = sourceRange.to;
  82160. var sourceKeys = source.animations[0].getKeys();
  82161. // rescaling prep
  82162. var sourceBoneLength = source.length;
  82163. var sourceParent = source.getParent();
  82164. var parent = this.getParent();
  82165. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  82166. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  82167. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  82168. var destKeys = this.animations[0].getKeys();
  82169. // loop vars declaration
  82170. var orig;
  82171. var origTranslation;
  82172. var mat;
  82173. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  82174. orig = sourceKeys[key];
  82175. if (orig.frame >= from && orig.frame <= to) {
  82176. if (rescaleAsRequired) {
  82177. mat = orig.value.clone();
  82178. // scale based on parent ratio, when bone has parent
  82179. if (parentScalingReqd) {
  82180. origTranslation = mat.getTranslation();
  82181. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  82182. // scale based on skeleton dimension ratio when root bone, and value is passed
  82183. }
  82184. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  82185. origTranslation = mat.getTranslation();
  82186. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  82187. // use original when root bone, and no data for skelDimensionsRatio
  82188. }
  82189. else {
  82190. mat = orig.value;
  82191. }
  82192. }
  82193. else {
  82194. mat = orig.value;
  82195. }
  82196. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  82197. }
  82198. }
  82199. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  82200. return true;
  82201. };
  82202. /**
  82203. * Translate the bone in local or world space
  82204. * @param vec The amount to translate the bone
  82205. * @param space The space that the translation is in
  82206. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82207. */
  82208. Bone.prototype.translate = function (vec, space, mesh) {
  82209. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82210. var lm = this.getLocalMatrix();
  82211. if (space == BABYLON.Space.LOCAL) {
  82212. lm.m[12] += vec.x;
  82213. lm.m[13] += vec.y;
  82214. lm.m[14] += vec.z;
  82215. }
  82216. else {
  82217. var wm = null;
  82218. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82219. if (mesh) {
  82220. wm = mesh.getWorldMatrix();
  82221. }
  82222. this._skeleton.computeAbsoluteTransforms();
  82223. var tmat = Bone._tmpMats[0];
  82224. var tvec = Bone._tmpVecs[0];
  82225. if (this._parent) {
  82226. if (mesh && wm) {
  82227. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82228. tmat.multiplyToRef(wm, tmat);
  82229. }
  82230. else {
  82231. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82232. }
  82233. }
  82234. tmat.m[12] = 0;
  82235. tmat.m[13] = 0;
  82236. tmat.m[14] = 0;
  82237. tmat.invert();
  82238. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  82239. lm.m[12] += tvec.x;
  82240. lm.m[13] += tvec.y;
  82241. lm.m[14] += tvec.z;
  82242. }
  82243. this._markAsDirtyAndDecompose();
  82244. };
  82245. /**
  82246. * Set the postion of the bone in local or world space
  82247. * @param position The position to set the bone
  82248. * @param space The space that the position is in
  82249. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82250. */
  82251. Bone.prototype.setPosition = function (position, space, mesh) {
  82252. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82253. var lm = this.getLocalMatrix();
  82254. if (space == BABYLON.Space.LOCAL) {
  82255. lm.m[12] = position.x;
  82256. lm.m[13] = position.y;
  82257. lm.m[14] = position.z;
  82258. }
  82259. else {
  82260. var wm = null;
  82261. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82262. if (mesh) {
  82263. wm = mesh.getWorldMatrix();
  82264. }
  82265. this._skeleton.computeAbsoluteTransforms();
  82266. var tmat = Bone._tmpMats[0];
  82267. var vec = Bone._tmpVecs[0];
  82268. if (this._parent) {
  82269. if (mesh && wm) {
  82270. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82271. tmat.multiplyToRef(wm, tmat);
  82272. }
  82273. else {
  82274. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82275. }
  82276. }
  82277. tmat.invert();
  82278. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  82279. lm.m[12] = vec.x;
  82280. lm.m[13] = vec.y;
  82281. lm.m[14] = vec.z;
  82282. }
  82283. this._markAsDirtyAndDecompose();
  82284. };
  82285. /**
  82286. * Set the absolute position of the bone (world space)
  82287. * @param position The position to set the bone
  82288. * @param mesh The mesh that this bone is attached to
  82289. */
  82290. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  82291. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  82292. };
  82293. /**
  82294. * Scale the bone on the x, y and z axes (in local space)
  82295. * @param x The amount to scale the bone on the x axis
  82296. * @param y The amount to scale the bone on the y axis
  82297. * @param z The amount to scale the bone on the z axis
  82298. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  82299. */
  82300. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  82301. if (scaleChildren === void 0) { scaleChildren = false; }
  82302. var locMat = this.getLocalMatrix();
  82303. // Apply new scaling on top of current local matrix
  82304. var scaleMat = Bone._tmpMats[0];
  82305. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  82306. scaleMat.multiplyToRef(locMat, locMat);
  82307. // Invert scaling matrix and apply the inverse to all children
  82308. scaleMat.invert();
  82309. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  82310. var child = _a[_i];
  82311. var cm = child.getLocalMatrix();
  82312. cm.multiplyToRef(scaleMat, cm);
  82313. cm.m[12] *= x;
  82314. cm.m[13] *= y;
  82315. cm.m[14] *= z;
  82316. child._markAsDirtyAndDecompose();
  82317. }
  82318. this._markAsDirtyAndDecompose();
  82319. if (scaleChildren) {
  82320. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  82321. var child = _c[_b];
  82322. child.scale(x, y, z, scaleChildren);
  82323. }
  82324. }
  82325. };
  82326. /**
  82327. * Set the bone scaling in local space
  82328. * @param scale defines the scaling vector
  82329. */
  82330. Bone.prototype.setScale = function (scale) {
  82331. this._decompose();
  82332. this._localScaling.copyFrom(scale);
  82333. this._markAsDirtyAndCompose();
  82334. };
  82335. /**
  82336. * Gets the current scaling in local space
  82337. * @returns the current scaling vector
  82338. */
  82339. Bone.prototype.getScale = function () {
  82340. this._decompose();
  82341. return this._localScaling;
  82342. };
  82343. /**
  82344. * Gets the current scaling in local space and stores it in a target vector
  82345. * @param result defines the target vector
  82346. */
  82347. Bone.prototype.getScaleToRef = function (result) {
  82348. this._decompose();
  82349. result.copyFrom(this._localScaling);
  82350. };
  82351. /**
  82352. * Set the yaw, pitch, and roll of the bone in local or world space
  82353. * @param yaw The rotation of the bone on the y axis
  82354. * @param pitch The rotation of the bone on the x axis
  82355. * @param roll The rotation of the bone on the z axis
  82356. * @param space The space that the axes of rotation are in
  82357. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82358. */
  82359. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  82360. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82361. if (space === BABYLON.Space.LOCAL) {
  82362. var quat = Bone._tmpQuat;
  82363. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  82364. this.setRotationQuaternion(quat, space, mesh);
  82365. return;
  82366. }
  82367. var rotMatInv = Bone._tmpMats[0];
  82368. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82369. return;
  82370. }
  82371. var rotMat = Bone._tmpMats[1];
  82372. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  82373. rotMatInv.multiplyToRef(rotMat, rotMat);
  82374. this._rotateWithMatrix(rotMat, space, mesh);
  82375. };
  82376. /**
  82377. * Add a rotation to the bone on an axis in local or world space
  82378. * @param axis The axis to rotate the bone on
  82379. * @param amount The amount to rotate the bone
  82380. * @param space The space that the axis is in
  82381. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82382. */
  82383. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  82384. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82385. var rmat = Bone._tmpMats[0];
  82386. rmat.m[12] = 0;
  82387. rmat.m[13] = 0;
  82388. rmat.m[14] = 0;
  82389. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  82390. this._rotateWithMatrix(rmat, space, mesh);
  82391. };
  82392. /**
  82393. * Set the rotation of the bone to a particular axis angle in local or world space
  82394. * @param axis The axis to rotate the bone on
  82395. * @param angle The angle that the bone should be rotated to
  82396. * @param space The space that the axis is in
  82397. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82398. */
  82399. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  82400. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82401. if (space === BABYLON.Space.LOCAL) {
  82402. var quat = Bone._tmpQuat;
  82403. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  82404. this.setRotationQuaternion(quat, space, mesh);
  82405. return;
  82406. }
  82407. var rotMatInv = Bone._tmpMats[0];
  82408. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82409. return;
  82410. }
  82411. var rotMat = Bone._tmpMats[1];
  82412. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  82413. rotMatInv.multiplyToRef(rotMat, rotMat);
  82414. this._rotateWithMatrix(rotMat, space, mesh);
  82415. };
  82416. /**
  82417. * Set the euler rotation of the bone in local of world space
  82418. * @param rotation The euler rotation that the bone should be set to
  82419. * @param space The space that the rotation is in
  82420. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82421. */
  82422. Bone.prototype.setRotation = function (rotation, space, mesh) {
  82423. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82424. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  82425. };
  82426. /**
  82427. * Set the quaternion rotation of the bone in local of world space
  82428. * @param quat The quaternion rotation that the bone should be set to
  82429. * @param space The space that the rotation is in
  82430. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82431. */
  82432. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  82433. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82434. if (space === BABYLON.Space.LOCAL) {
  82435. this._decompose();
  82436. this._localRotation.copyFrom(quat);
  82437. this._markAsDirtyAndCompose();
  82438. return;
  82439. }
  82440. var rotMatInv = Bone._tmpMats[0];
  82441. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82442. return;
  82443. }
  82444. var rotMat = Bone._tmpMats[1];
  82445. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  82446. rotMatInv.multiplyToRef(rotMat, rotMat);
  82447. this._rotateWithMatrix(rotMat, space, mesh);
  82448. };
  82449. /**
  82450. * Set the rotation matrix of the bone in local of world space
  82451. * @param rotMat The rotation matrix that the bone should be set to
  82452. * @param space The space that the rotation is in
  82453. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82454. */
  82455. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  82456. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82457. if (space === BABYLON.Space.LOCAL) {
  82458. var quat = Bone._tmpQuat;
  82459. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  82460. this.setRotationQuaternion(quat, space, mesh);
  82461. return;
  82462. }
  82463. var rotMatInv = Bone._tmpMats[0];
  82464. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82465. return;
  82466. }
  82467. var rotMat2 = Bone._tmpMats[1];
  82468. rotMat2.copyFrom(rotMat);
  82469. rotMatInv.multiplyToRef(rotMat, rotMat2);
  82470. this._rotateWithMatrix(rotMat2, space, mesh);
  82471. };
  82472. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  82473. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82474. var lmat = this.getLocalMatrix();
  82475. var lx = lmat.m[12];
  82476. var ly = lmat.m[13];
  82477. var lz = lmat.m[14];
  82478. var parent = this.getParent();
  82479. var parentScale = Bone._tmpMats[3];
  82480. var parentScaleInv = Bone._tmpMats[4];
  82481. if (parent && space == BABYLON.Space.WORLD) {
  82482. if (mesh) {
  82483. parentScale.copyFrom(mesh.getWorldMatrix());
  82484. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  82485. }
  82486. else {
  82487. parentScale.copyFrom(parent.getAbsoluteTransform());
  82488. }
  82489. parentScaleInv.copyFrom(parentScale);
  82490. parentScaleInv.invert();
  82491. lmat.multiplyToRef(parentScale, lmat);
  82492. lmat.multiplyToRef(rmat, lmat);
  82493. lmat.multiplyToRef(parentScaleInv, lmat);
  82494. }
  82495. else {
  82496. if (space == BABYLON.Space.WORLD && mesh) {
  82497. parentScale.copyFrom(mesh.getWorldMatrix());
  82498. parentScaleInv.copyFrom(parentScale);
  82499. parentScaleInv.invert();
  82500. lmat.multiplyToRef(parentScale, lmat);
  82501. lmat.multiplyToRef(rmat, lmat);
  82502. lmat.multiplyToRef(parentScaleInv, lmat);
  82503. }
  82504. else {
  82505. lmat.multiplyToRef(rmat, lmat);
  82506. }
  82507. }
  82508. lmat.m[12] = lx;
  82509. lmat.m[13] = ly;
  82510. lmat.m[14] = lz;
  82511. this.computeAbsoluteTransforms();
  82512. this._markAsDirtyAndDecompose();
  82513. };
  82514. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  82515. var scaleMatrix = Bone._tmpMats[2];
  82516. rotMatInv.copyFrom(this.getAbsoluteTransform());
  82517. if (mesh) {
  82518. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  82519. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  82520. }
  82521. rotMatInv.invert();
  82522. if (isNaN(rotMatInv.m[0])) {
  82523. // Matrix failed to invert.
  82524. // This can happen if scale is zero for example.
  82525. return false;
  82526. }
  82527. scaleMatrix.m[0] *= this._scalingDeterminant;
  82528. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  82529. return true;
  82530. };
  82531. /**
  82532. * Get the position of the bone in local or world space
  82533. * @param space The space that the returned position is in
  82534. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82535. * @returns The position of the bone
  82536. */
  82537. Bone.prototype.getPosition = function (space, mesh) {
  82538. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82539. if (mesh === void 0) { mesh = null; }
  82540. var pos = BABYLON.Vector3.Zero();
  82541. this.getPositionToRef(space, mesh, pos);
  82542. return pos;
  82543. };
  82544. /**
  82545. * Copy the position of the bone to a vector3 in local or world space
  82546. * @param space The space that the returned position is in
  82547. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82548. * @param result The vector3 to copy the position to
  82549. */
  82550. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  82551. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82552. if (space == BABYLON.Space.LOCAL) {
  82553. var lm = this.getLocalMatrix();
  82554. result.x = lm.m[12];
  82555. result.y = lm.m[13];
  82556. result.z = lm.m[14];
  82557. }
  82558. else {
  82559. var wm = null;
  82560. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82561. if (mesh) {
  82562. wm = mesh.getWorldMatrix();
  82563. }
  82564. this._skeleton.computeAbsoluteTransforms();
  82565. var tmat = Bone._tmpMats[0];
  82566. if (mesh && wm) {
  82567. tmat.copyFrom(this.getAbsoluteTransform());
  82568. tmat.multiplyToRef(wm, tmat);
  82569. }
  82570. else {
  82571. tmat = this.getAbsoluteTransform();
  82572. }
  82573. result.x = tmat.m[12];
  82574. result.y = tmat.m[13];
  82575. result.z = tmat.m[14];
  82576. }
  82577. };
  82578. /**
  82579. * Get the absolute position of the bone (world space)
  82580. * @param mesh The mesh that this bone is attached to
  82581. * @returns The absolute position of the bone
  82582. */
  82583. Bone.prototype.getAbsolutePosition = function (mesh) {
  82584. if (mesh === void 0) { mesh = null; }
  82585. var pos = BABYLON.Vector3.Zero();
  82586. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  82587. return pos;
  82588. };
  82589. /**
  82590. * Copy the absolute position of the bone (world space) to the result param
  82591. * @param mesh The mesh that this bone is attached to
  82592. * @param result The vector3 to copy the absolute position to
  82593. */
  82594. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  82595. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  82596. };
  82597. /**
  82598. * Compute the absolute transforms of this bone and its children
  82599. */
  82600. Bone.prototype.computeAbsoluteTransforms = function () {
  82601. this._compose();
  82602. if (this._parent) {
  82603. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82604. }
  82605. else {
  82606. this._absoluteTransform.copyFrom(this._localMatrix);
  82607. var poseMatrix = this._skeleton.getPoseMatrix();
  82608. if (poseMatrix) {
  82609. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  82610. }
  82611. }
  82612. var children = this.children;
  82613. var len = children.length;
  82614. for (var i = 0; i < len; i++) {
  82615. children[i].computeAbsoluteTransforms();
  82616. }
  82617. };
  82618. /**
  82619. * Get the world direction from an axis that is in the local space of the bone
  82620. * @param localAxis The local direction that is used to compute the world direction
  82621. * @param mesh The mesh that this bone is attached to
  82622. * @returns The world direction
  82623. */
  82624. Bone.prototype.getDirection = function (localAxis, mesh) {
  82625. if (mesh === void 0) { mesh = null; }
  82626. var result = BABYLON.Vector3.Zero();
  82627. this.getDirectionToRef(localAxis, mesh, result);
  82628. return result;
  82629. };
  82630. /**
  82631. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  82632. * @param localAxis The local direction that is used to compute the world direction
  82633. * @param mesh The mesh that this bone is attached to
  82634. * @param result The vector3 that the world direction will be copied to
  82635. */
  82636. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  82637. if (mesh === void 0) { mesh = null; }
  82638. var wm = null;
  82639. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82640. if (mesh) {
  82641. wm = mesh.getWorldMatrix();
  82642. }
  82643. this._skeleton.computeAbsoluteTransforms();
  82644. var mat = Bone._tmpMats[0];
  82645. mat.copyFrom(this.getAbsoluteTransform());
  82646. if (mesh && wm) {
  82647. mat.multiplyToRef(wm, mat);
  82648. }
  82649. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  82650. result.normalize();
  82651. };
  82652. /**
  82653. * Get the euler rotation of the bone in local or world space
  82654. * @param space The space that the rotation should be in
  82655. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82656. * @returns The euler rotation
  82657. */
  82658. Bone.prototype.getRotation = function (space, mesh) {
  82659. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82660. if (mesh === void 0) { mesh = null; }
  82661. var result = BABYLON.Vector3.Zero();
  82662. this.getRotationToRef(space, mesh, result);
  82663. return result;
  82664. };
  82665. /**
  82666. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  82667. * @param space The space that the rotation should be in
  82668. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82669. * @param result The vector3 that the rotation should be copied to
  82670. */
  82671. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  82672. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82673. if (mesh === void 0) { mesh = null; }
  82674. var quat = Bone._tmpQuat;
  82675. this.getRotationQuaternionToRef(space, mesh, quat);
  82676. quat.toEulerAnglesToRef(result);
  82677. };
  82678. /**
  82679. * Get the quaternion rotation of the bone in either local or world space
  82680. * @param space The space that the rotation should be in
  82681. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82682. * @returns The quaternion rotation
  82683. */
  82684. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  82685. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82686. if (mesh === void 0) { mesh = null; }
  82687. var result = BABYLON.Quaternion.Identity();
  82688. this.getRotationQuaternionToRef(space, mesh, result);
  82689. return result;
  82690. };
  82691. /**
  82692. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  82693. * @param space The space that the rotation should be in
  82694. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82695. * @param result The quaternion that the rotation should be copied to
  82696. */
  82697. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  82698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82699. if (mesh === void 0) { mesh = null; }
  82700. if (space == BABYLON.Space.LOCAL) {
  82701. this._decompose();
  82702. result.copyFrom(this._localRotation);
  82703. }
  82704. else {
  82705. var mat = Bone._tmpMats[0];
  82706. var amat = this.getAbsoluteTransform();
  82707. if (mesh) {
  82708. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  82709. }
  82710. else {
  82711. mat.copyFrom(amat);
  82712. }
  82713. mat.m[0] *= this._scalingDeterminant;
  82714. mat.m[1] *= this._scalingDeterminant;
  82715. mat.m[2] *= this._scalingDeterminant;
  82716. mat.decompose(undefined, result, undefined);
  82717. }
  82718. };
  82719. /**
  82720. * Get the rotation matrix of the bone in local or world space
  82721. * @param space The space that the rotation should be in
  82722. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82723. * @returns The rotation matrix
  82724. */
  82725. Bone.prototype.getRotationMatrix = function (space, mesh) {
  82726. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82727. var result = BABYLON.Matrix.Identity();
  82728. this.getRotationMatrixToRef(space, mesh, result);
  82729. return result;
  82730. };
  82731. /**
  82732. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  82733. * @param space The space that the rotation should be in
  82734. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82735. * @param result The quaternion that the rotation should be copied to
  82736. */
  82737. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  82738. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82739. if (space == BABYLON.Space.LOCAL) {
  82740. this.getLocalMatrix().getRotationMatrixToRef(result);
  82741. }
  82742. else {
  82743. var mat = Bone._tmpMats[0];
  82744. var amat = this.getAbsoluteTransform();
  82745. if (mesh) {
  82746. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  82747. }
  82748. else {
  82749. mat.copyFrom(amat);
  82750. }
  82751. mat.m[0] *= this._scalingDeterminant;
  82752. mat.m[1] *= this._scalingDeterminant;
  82753. mat.m[2] *= this._scalingDeterminant;
  82754. mat.getRotationMatrixToRef(result);
  82755. }
  82756. };
  82757. /**
  82758. * Get the world position of a point that is in the local space of the bone
  82759. * @param position The local position
  82760. * @param mesh The mesh that this bone is attached to
  82761. * @returns The world position
  82762. */
  82763. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  82764. if (mesh === void 0) { mesh = null; }
  82765. var result = BABYLON.Vector3.Zero();
  82766. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  82767. return result;
  82768. };
  82769. /**
  82770. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  82771. * @param position The local position
  82772. * @param mesh The mesh that this bone is attached to
  82773. * @param result The vector3 that the world position should be copied to
  82774. */
  82775. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  82776. if (mesh === void 0) { mesh = null; }
  82777. var wm = null;
  82778. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82779. if (mesh) {
  82780. wm = mesh.getWorldMatrix();
  82781. }
  82782. this._skeleton.computeAbsoluteTransforms();
  82783. var tmat = Bone._tmpMats[0];
  82784. if (mesh && wm) {
  82785. tmat.copyFrom(this.getAbsoluteTransform());
  82786. tmat.multiplyToRef(wm, tmat);
  82787. }
  82788. else {
  82789. tmat = this.getAbsoluteTransform();
  82790. }
  82791. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  82792. };
  82793. /**
  82794. * Get the local position of a point that is in world space
  82795. * @param position The world position
  82796. * @param mesh The mesh that this bone is attached to
  82797. * @returns The local position
  82798. */
  82799. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  82800. if (mesh === void 0) { mesh = null; }
  82801. var result = BABYLON.Vector3.Zero();
  82802. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  82803. return result;
  82804. };
  82805. /**
  82806. * Get the local position of a point that is in world space and copy it to the result param
  82807. * @param position The world position
  82808. * @param mesh The mesh that this bone is attached to
  82809. * @param result The vector3 that the local position should be copied to
  82810. */
  82811. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  82812. if (mesh === void 0) { mesh = null; }
  82813. var wm = null;
  82814. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82815. if (mesh) {
  82816. wm = mesh.getWorldMatrix();
  82817. }
  82818. this._skeleton.computeAbsoluteTransforms();
  82819. var tmat = Bone._tmpMats[0];
  82820. tmat.copyFrom(this.getAbsoluteTransform());
  82821. if (mesh && wm) {
  82822. tmat.multiplyToRef(wm, tmat);
  82823. }
  82824. tmat.invert();
  82825. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  82826. };
  82827. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82828. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  82829. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82830. return Bone;
  82831. }(BABYLON.Node));
  82832. BABYLON.Bone = Bone;
  82833. })(BABYLON || (BABYLON = {}));
  82834. //# sourceMappingURL=babylon.bone.js.map
  82835. var BABYLON;
  82836. (function (BABYLON) {
  82837. /**
  82838. * Class used to apply inverse kinematics to bones
  82839. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  82840. */
  82841. var BoneIKController = /** @class */ (function () {
  82842. /**
  82843. * Creates a new BoneIKController
  82844. * @param mesh defines the mesh to control
  82845. * @param bone defines the bone to control
  82846. * @param options defines options to set up the controller
  82847. */
  82848. function BoneIKController(mesh, bone, options) {
  82849. /**
  82850. * Gets or sets the target position
  82851. */
  82852. this.targetPosition = BABYLON.Vector3.Zero();
  82853. /**
  82854. * Gets or sets the pole target position
  82855. */
  82856. this.poleTargetPosition = BABYLON.Vector3.Zero();
  82857. /**
  82858. * Gets or sets the pole target local offset
  82859. */
  82860. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  82861. /**
  82862. * Gets or sets the pole angle
  82863. */
  82864. this.poleAngle = 0;
  82865. /**
  82866. * 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)
  82867. */
  82868. this.slerpAmount = 1;
  82869. this._bone1Quat = BABYLON.Quaternion.Identity();
  82870. this._bone1Mat = BABYLON.Matrix.Identity();
  82871. this._bone2Ang = Math.PI;
  82872. this._maxAngle = Math.PI;
  82873. this._rightHandedSystem = false;
  82874. this._bendAxis = BABYLON.Vector3.Right();
  82875. this._slerping = false;
  82876. this._adjustRoll = 0;
  82877. this._bone2 = bone;
  82878. this._bone1 = bone.getParent();
  82879. if (!this._bone1) {
  82880. return;
  82881. }
  82882. this.mesh = mesh;
  82883. var bonePos = bone.getPosition();
  82884. if (bone.getAbsoluteTransform().determinant() > 0) {
  82885. this._rightHandedSystem = true;
  82886. this._bendAxis.x = 0;
  82887. this._bendAxis.y = 0;
  82888. this._bendAxis.z = -1;
  82889. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  82890. this._adjustRoll = Math.PI * .5;
  82891. this._bendAxis.z = 1;
  82892. }
  82893. }
  82894. if (this._bone1.length) {
  82895. var boneScale1 = this._bone1.getScale();
  82896. var boneScale2 = this._bone2.getScale();
  82897. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  82898. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  82899. }
  82900. else if (this._bone1.children[0]) {
  82901. mesh.computeWorldMatrix(true);
  82902. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  82903. var pos2 = this._bone2.getAbsolutePosition(mesh);
  82904. var pos3 = this._bone1.getAbsolutePosition(mesh);
  82905. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  82906. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  82907. }
  82908. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  82909. this.maxAngle = Math.PI;
  82910. if (options) {
  82911. if (options.targetMesh) {
  82912. this.targetMesh = options.targetMesh;
  82913. this.targetMesh.computeWorldMatrix(true);
  82914. }
  82915. if (options.poleTargetMesh) {
  82916. this.poleTargetMesh = options.poleTargetMesh;
  82917. this.poleTargetMesh.computeWorldMatrix(true);
  82918. }
  82919. else if (options.poleTargetBone) {
  82920. this.poleTargetBone = options.poleTargetBone;
  82921. }
  82922. else if (this._bone1.getParent()) {
  82923. this.poleTargetBone = this._bone1.getParent();
  82924. }
  82925. if (options.poleTargetLocalOffset) {
  82926. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  82927. }
  82928. if (options.poleAngle) {
  82929. this.poleAngle = options.poleAngle;
  82930. }
  82931. if (options.bendAxis) {
  82932. this._bendAxis.copyFrom(options.bendAxis);
  82933. }
  82934. if (options.maxAngle) {
  82935. this.maxAngle = options.maxAngle;
  82936. }
  82937. if (options.slerpAmount) {
  82938. this.slerpAmount = options.slerpAmount;
  82939. }
  82940. }
  82941. }
  82942. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  82943. /**
  82944. * Gets or sets maximum allowed angle
  82945. */
  82946. get: function () {
  82947. return this._maxAngle;
  82948. },
  82949. set: function (value) {
  82950. this._setMaxAngle(value);
  82951. },
  82952. enumerable: true,
  82953. configurable: true
  82954. });
  82955. BoneIKController.prototype._setMaxAngle = function (ang) {
  82956. if (ang < 0) {
  82957. ang = 0;
  82958. }
  82959. if (ang > Math.PI || ang == undefined) {
  82960. ang = Math.PI;
  82961. }
  82962. this._maxAngle = ang;
  82963. var a = this._bone1Length;
  82964. var b = this._bone2Length;
  82965. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  82966. };
  82967. /**
  82968. * Force the controller to update the bones
  82969. */
  82970. BoneIKController.prototype.update = function () {
  82971. var bone1 = this._bone1;
  82972. if (!bone1) {
  82973. return;
  82974. }
  82975. var target = this.targetPosition;
  82976. var poleTarget = this.poleTargetPosition;
  82977. var mat1 = BoneIKController._tmpMats[0];
  82978. var mat2 = BoneIKController._tmpMats[1];
  82979. if (this.targetMesh) {
  82980. target.copyFrom(this.targetMesh.getAbsolutePosition());
  82981. }
  82982. if (this.poleTargetBone) {
  82983. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  82984. }
  82985. else if (this.poleTargetMesh) {
  82986. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  82987. }
  82988. var bonePos = BoneIKController._tmpVecs[0];
  82989. var zaxis = BoneIKController._tmpVecs[1];
  82990. var xaxis = BoneIKController._tmpVecs[2];
  82991. var yaxis = BoneIKController._tmpVecs[3];
  82992. var upAxis = BoneIKController._tmpVecs[4];
  82993. var _tmpQuat = BoneIKController._tmpQuat;
  82994. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  82995. poleTarget.subtractToRef(bonePos, upAxis);
  82996. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  82997. upAxis.y = 1;
  82998. }
  82999. else {
  83000. upAxis.normalize();
  83001. }
  83002. target.subtractToRef(bonePos, yaxis);
  83003. yaxis.normalize();
  83004. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  83005. zaxis.normalize();
  83006. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  83007. xaxis.normalize();
  83008. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  83009. var a = this._bone1Length;
  83010. var b = this._bone2Length;
  83011. var c = BABYLON.Vector3.Distance(bonePos, target);
  83012. if (this._maxReach > 0) {
  83013. c = Math.min(this._maxReach, c);
  83014. }
  83015. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  83016. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  83017. if (acosa > 1) {
  83018. acosa = 1;
  83019. }
  83020. if (acosb > 1) {
  83021. acosb = 1;
  83022. }
  83023. if (acosa < -1) {
  83024. acosa = -1;
  83025. }
  83026. if (acosb < -1) {
  83027. acosb = -1;
  83028. }
  83029. var angA = Math.acos(acosa);
  83030. var angB = Math.acos(acosb);
  83031. var angC = -angA - angB;
  83032. if (this._rightHandedSystem) {
  83033. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  83034. mat2.multiplyToRef(mat1, mat1);
  83035. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  83036. mat2.multiplyToRef(mat1, mat1);
  83037. }
  83038. else {
  83039. var _tmpVec = BoneIKController._tmpVecs[5];
  83040. _tmpVec.copyFrom(this._bendAxis);
  83041. _tmpVec.x *= -1;
  83042. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  83043. mat2.multiplyToRef(mat1, mat1);
  83044. }
  83045. if (this.poleAngle) {
  83046. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  83047. mat1.multiplyToRef(mat2, mat1);
  83048. }
  83049. if (this._bone1) {
  83050. if (this.slerpAmount < 1) {
  83051. if (!this._slerping) {
  83052. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  83053. }
  83054. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  83055. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  83056. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  83057. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  83058. this._slerping = true;
  83059. }
  83060. else {
  83061. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  83062. this._bone1Mat.copyFrom(mat1);
  83063. this._slerping = false;
  83064. }
  83065. }
  83066. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  83067. this._bone2Ang = angC;
  83068. };
  83069. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83070. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  83071. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83072. return BoneIKController;
  83073. }());
  83074. BABYLON.BoneIKController = BoneIKController;
  83075. })(BABYLON || (BABYLON = {}));
  83076. //# sourceMappingURL=babylon.boneIKController.js.map
  83077. var BABYLON;
  83078. (function (BABYLON) {
  83079. /**
  83080. * Class used to make a bone look toward a point in space
  83081. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  83082. */
  83083. var BoneLookController = /** @class */ (function () {
  83084. /**
  83085. * Create a BoneLookController
  83086. * @param mesh the mesh that the bone belongs to
  83087. * @param bone the bone that will be looking to the target
  83088. * @param target the target Vector3 to look at
  83089. * @param settings optional settings:
  83090. * * maxYaw: the maximum angle the bone will yaw to
  83091. * * minYaw: the minimum angle the bone will yaw to
  83092. * * maxPitch: the maximum angle the bone will pitch to
  83093. * * minPitch: the minimum angle the bone will yaw to
  83094. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  83095. * * upAxis: the up axis of the coordinate system
  83096. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  83097. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  83098. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  83099. * * adjustYaw: used to make an adjustment to the yaw of the bone
  83100. * * adjustPitch: used to make an adjustment to the pitch of the bone
  83101. * * adjustRoll: used to make an adjustment to the roll of the bone
  83102. **/
  83103. function BoneLookController(mesh, bone, target, options) {
  83104. /**
  83105. * The up axis of the coordinate system that is used when the bone is rotated
  83106. */
  83107. this.upAxis = BABYLON.Vector3.Up();
  83108. /**
  83109. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  83110. */
  83111. this.upAxisSpace = BABYLON.Space.LOCAL;
  83112. /**
  83113. * Used to make an adjustment to the yaw of the bone
  83114. */
  83115. this.adjustYaw = 0;
  83116. /**
  83117. * Used to make an adjustment to the pitch of the bone
  83118. */
  83119. this.adjustPitch = 0;
  83120. /**
  83121. * Used to make an adjustment to the roll of the bone
  83122. */
  83123. this.adjustRoll = 0;
  83124. /**
  83125. * 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)
  83126. */
  83127. this.slerpAmount = 1;
  83128. this._boneQuat = BABYLON.Quaternion.Identity();
  83129. this._slerping = false;
  83130. this._firstFrameSkipped = false;
  83131. this._fowardAxis = BABYLON.Vector3.Forward();
  83132. this.mesh = mesh;
  83133. this.bone = bone;
  83134. this.target = target;
  83135. if (options) {
  83136. if (options.adjustYaw) {
  83137. this.adjustYaw = options.adjustYaw;
  83138. }
  83139. if (options.adjustPitch) {
  83140. this.adjustPitch = options.adjustPitch;
  83141. }
  83142. if (options.adjustRoll) {
  83143. this.adjustRoll = options.adjustRoll;
  83144. }
  83145. if (options.maxYaw != null) {
  83146. this.maxYaw = options.maxYaw;
  83147. }
  83148. else {
  83149. this.maxYaw = Math.PI;
  83150. }
  83151. if (options.minYaw != null) {
  83152. this.minYaw = options.minYaw;
  83153. }
  83154. else {
  83155. this.minYaw = -Math.PI;
  83156. }
  83157. if (options.maxPitch != null) {
  83158. this.maxPitch = options.maxPitch;
  83159. }
  83160. else {
  83161. this.maxPitch = Math.PI;
  83162. }
  83163. if (options.minPitch != null) {
  83164. this.minPitch = options.minPitch;
  83165. }
  83166. else {
  83167. this.minPitch = -Math.PI;
  83168. }
  83169. if (options.slerpAmount != null) {
  83170. this.slerpAmount = options.slerpAmount;
  83171. }
  83172. if (options.upAxis != null) {
  83173. this.upAxis = options.upAxis;
  83174. }
  83175. if (options.upAxisSpace != null) {
  83176. this.upAxisSpace = options.upAxisSpace;
  83177. }
  83178. if (options.yawAxis != null || options.pitchAxis != null) {
  83179. var newYawAxis = BABYLON.Axis.Y;
  83180. var newPitchAxis = BABYLON.Axis.X;
  83181. if (options.yawAxis != null) {
  83182. newYawAxis = options.yawAxis.clone();
  83183. newYawAxis.normalize();
  83184. }
  83185. if (options.pitchAxis != null) {
  83186. newPitchAxis = options.pitchAxis.clone();
  83187. newPitchAxis.normalize();
  83188. }
  83189. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  83190. this._transformYawPitch = BABYLON.Matrix.Identity();
  83191. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  83192. this._transformYawPitchInv = this._transformYawPitch.clone();
  83193. this._transformYawPitch.invert();
  83194. }
  83195. }
  83196. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  83197. this.upAxisSpace = BABYLON.Space.LOCAL;
  83198. }
  83199. }
  83200. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  83201. /**
  83202. * Gets or sets the minimum yaw angle that the bone can look to
  83203. */
  83204. get: function () {
  83205. return this._minYaw;
  83206. },
  83207. set: function (value) {
  83208. this._minYaw = value;
  83209. this._minYawSin = Math.sin(value);
  83210. this._minYawCos = Math.cos(value);
  83211. if (this._maxYaw != null) {
  83212. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  83213. this._yawRange = this._maxYaw - this._minYaw;
  83214. }
  83215. },
  83216. enumerable: true,
  83217. configurable: true
  83218. });
  83219. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  83220. /**
  83221. * Gets or sets the maximum yaw angle that the bone can look to
  83222. */
  83223. get: function () {
  83224. return this._maxYaw;
  83225. },
  83226. set: function (value) {
  83227. this._maxYaw = value;
  83228. this._maxYawSin = Math.sin(value);
  83229. this._maxYawCos = Math.cos(value);
  83230. if (this._minYaw != null) {
  83231. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  83232. this._yawRange = this._maxYaw - this._minYaw;
  83233. }
  83234. },
  83235. enumerable: true,
  83236. configurable: true
  83237. });
  83238. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  83239. /**
  83240. * Gets or sets the minimum pitch angle that the bone can look to
  83241. */
  83242. get: function () {
  83243. return this._minPitch;
  83244. },
  83245. set: function (value) {
  83246. this._minPitch = value;
  83247. this._minPitchTan = Math.tan(value);
  83248. },
  83249. enumerable: true,
  83250. configurable: true
  83251. });
  83252. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  83253. /**
  83254. * Gets or sets the maximum pitch angle that the bone can look to
  83255. */
  83256. get: function () {
  83257. return this._maxPitch;
  83258. },
  83259. set: function (value) {
  83260. this._maxPitch = value;
  83261. this._maxPitchTan = Math.tan(value);
  83262. },
  83263. enumerable: true,
  83264. configurable: true
  83265. });
  83266. /**
  83267. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  83268. */
  83269. BoneLookController.prototype.update = function () {
  83270. //skip the first frame when slerping so that the mesh rotation is correct
  83271. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  83272. this._firstFrameSkipped = true;
  83273. return;
  83274. }
  83275. var bone = this.bone;
  83276. var bonePos = BoneLookController._tmpVecs[0];
  83277. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  83278. var target = this.target;
  83279. var _tmpMat1 = BoneLookController._tmpMats[0];
  83280. var _tmpMat2 = BoneLookController._tmpMats[1];
  83281. var mesh = this.mesh;
  83282. var parentBone = bone.getParent();
  83283. var upAxis = BoneLookController._tmpVecs[1];
  83284. upAxis.copyFrom(this.upAxis);
  83285. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  83286. if (this._transformYawPitch) {
  83287. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  83288. }
  83289. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  83290. }
  83291. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  83292. mesh.getDirectionToRef(upAxis, upAxis);
  83293. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  83294. upAxis.normalize();
  83295. }
  83296. }
  83297. var checkYaw = false;
  83298. var checkPitch = false;
  83299. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  83300. checkYaw = true;
  83301. }
  83302. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  83303. checkPitch = true;
  83304. }
  83305. if (checkYaw || checkPitch) {
  83306. var spaceMat = BoneLookController._tmpMats[2];
  83307. var spaceMatInv = BoneLookController._tmpMats[3];
  83308. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  83309. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  83310. }
  83311. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  83312. spaceMat.copyFrom(mesh.getWorldMatrix());
  83313. }
  83314. else {
  83315. var forwardAxis = BoneLookController._tmpVecs[2];
  83316. forwardAxis.copyFrom(this._fowardAxis);
  83317. if (this._transformYawPitch) {
  83318. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  83319. }
  83320. if (parentBone) {
  83321. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  83322. }
  83323. else {
  83324. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  83325. }
  83326. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  83327. rightAxis.normalize();
  83328. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  83329. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  83330. }
  83331. spaceMat.invertToRef(spaceMatInv);
  83332. var xzlen = null;
  83333. if (checkPitch) {
  83334. var localTarget = BoneLookController._tmpVecs[3];
  83335. target.subtractToRef(bonePos, localTarget);
  83336. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  83337. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83338. var pitch = Math.atan2(localTarget.y, xzlen);
  83339. var newPitch = pitch;
  83340. if (pitch > this._maxPitch) {
  83341. localTarget.y = this._maxPitchTan * xzlen;
  83342. newPitch = this._maxPitch;
  83343. }
  83344. else if (pitch < this._minPitch) {
  83345. localTarget.y = this._minPitchTan * xzlen;
  83346. newPitch = this._minPitch;
  83347. }
  83348. if (pitch != newPitch) {
  83349. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  83350. localTarget.addInPlace(bonePos);
  83351. target = localTarget;
  83352. }
  83353. }
  83354. if (checkYaw) {
  83355. var localTarget = BoneLookController._tmpVecs[4];
  83356. target.subtractToRef(bonePos, localTarget);
  83357. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  83358. var yaw = Math.atan2(localTarget.x, localTarget.z);
  83359. var newYaw = yaw;
  83360. if (yaw > this._maxYaw || yaw < this._minYaw) {
  83361. if (xzlen == null) {
  83362. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83363. }
  83364. if (this._yawRange > Math.PI) {
  83365. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  83366. localTarget.z = this._maxYawCos * xzlen;
  83367. localTarget.x = this._maxYawSin * xzlen;
  83368. newYaw = this._maxYaw;
  83369. }
  83370. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  83371. localTarget.z = this._minYawCos * xzlen;
  83372. localTarget.x = this._minYawSin * xzlen;
  83373. newYaw = this._minYaw;
  83374. }
  83375. }
  83376. else {
  83377. if (yaw > this._maxYaw) {
  83378. localTarget.z = this._maxYawCos * xzlen;
  83379. localTarget.x = this._maxYawSin * xzlen;
  83380. newYaw = this._maxYaw;
  83381. }
  83382. else if (yaw < this._minYaw) {
  83383. localTarget.z = this._minYawCos * xzlen;
  83384. localTarget.x = this._minYawSin * xzlen;
  83385. newYaw = this._minYaw;
  83386. }
  83387. }
  83388. }
  83389. if (this._slerping && this._yawRange > Math.PI) {
  83390. //are we going to be crossing into the min/max region?
  83391. var boneFwd = BoneLookController._tmpVecs[8];
  83392. boneFwd.copyFrom(BABYLON.Axis.Z);
  83393. if (this._transformYawPitch) {
  83394. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  83395. }
  83396. var boneRotMat = BoneLookController._tmpMats[4];
  83397. this._boneQuat.toRotationMatrix(boneRotMat);
  83398. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  83399. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  83400. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  83401. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  83402. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  83403. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  83404. if (angBtwTar > angBtwMidYaw) {
  83405. if (xzlen == null) {
  83406. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83407. }
  83408. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  83409. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  83410. if (angBtwMin < angBtwMax) {
  83411. newYaw = boneYaw + Math.PI * .75;
  83412. localTarget.z = Math.cos(newYaw) * xzlen;
  83413. localTarget.x = Math.sin(newYaw) * xzlen;
  83414. }
  83415. else {
  83416. newYaw = boneYaw - Math.PI * .75;
  83417. localTarget.z = Math.cos(newYaw) * xzlen;
  83418. localTarget.x = Math.sin(newYaw) * xzlen;
  83419. }
  83420. }
  83421. }
  83422. if (yaw != newYaw) {
  83423. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  83424. localTarget.addInPlace(bonePos);
  83425. target = localTarget;
  83426. }
  83427. }
  83428. }
  83429. var zaxis = BoneLookController._tmpVecs[5];
  83430. var xaxis = BoneLookController._tmpVecs[6];
  83431. var yaxis = BoneLookController._tmpVecs[7];
  83432. var _tmpQuat = BoneLookController._tmpQuat;
  83433. target.subtractToRef(bonePos, zaxis);
  83434. zaxis.normalize();
  83435. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  83436. xaxis.normalize();
  83437. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  83438. yaxis.normalize();
  83439. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  83440. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  83441. return;
  83442. }
  83443. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  83444. return;
  83445. }
  83446. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  83447. return;
  83448. }
  83449. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  83450. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  83451. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  83452. }
  83453. if (this.slerpAmount < 1) {
  83454. if (!this._slerping) {
  83455. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  83456. }
  83457. if (this._transformYawPitch) {
  83458. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  83459. }
  83460. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  83461. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  83462. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  83463. this._slerping = true;
  83464. }
  83465. else {
  83466. if (this._transformYawPitch) {
  83467. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  83468. }
  83469. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  83470. this._slerping = false;
  83471. }
  83472. };
  83473. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  83474. var angDiff = ang2 - ang1;
  83475. angDiff %= Math.PI * 2;
  83476. if (angDiff > Math.PI) {
  83477. angDiff -= Math.PI * 2;
  83478. }
  83479. else if (angDiff < -Math.PI) {
  83480. angDiff += Math.PI * 2;
  83481. }
  83482. return angDiff;
  83483. };
  83484. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  83485. ang1 %= (2 * Math.PI);
  83486. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  83487. ang2 %= (2 * Math.PI);
  83488. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  83489. var ab = 0;
  83490. if (ang1 < ang2) {
  83491. ab = ang2 - ang1;
  83492. }
  83493. else {
  83494. ab = ang1 - ang2;
  83495. }
  83496. if (ab > Math.PI) {
  83497. ab = Math.PI * 2 - ab;
  83498. }
  83499. return ab;
  83500. };
  83501. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  83502. ang %= (2 * Math.PI);
  83503. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  83504. ang1 %= (2 * Math.PI);
  83505. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  83506. ang2 %= (2 * Math.PI);
  83507. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  83508. if (ang1 < ang2) {
  83509. if (ang > ang1 && ang < ang2) {
  83510. return true;
  83511. }
  83512. }
  83513. else {
  83514. if (ang > ang2 && ang < ang1) {
  83515. return true;
  83516. }
  83517. }
  83518. return false;
  83519. };
  83520. 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()];
  83521. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  83522. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83523. return BoneLookController;
  83524. }());
  83525. BABYLON.BoneLookController = BoneLookController;
  83526. })(BABYLON || (BABYLON = {}));
  83527. //# sourceMappingURL=babylon.boneLookController.js.map
  83528. var BABYLON;
  83529. (function (BABYLON) {
  83530. /**
  83531. * Class used to handle skinning animations
  83532. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  83533. */
  83534. var Skeleton = /** @class */ (function () {
  83535. /**
  83536. * Creates a new skeleton
  83537. * @param name defines the skeleton name
  83538. * @param id defines the skeleton Id
  83539. * @param scene defines the hosting scene
  83540. */
  83541. function Skeleton(
  83542. /** defines the skeleton name */
  83543. name,
  83544. /** defines the skeleton Id */
  83545. id, scene) {
  83546. this.name = name;
  83547. this.id = id;
  83548. /**
  83549. * Gets the list of child bones
  83550. */
  83551. this.bones = new Array();
  83552. /**
  83553. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  83554. */
  83555. this.needInitialSkinMatrix = false;
  83556. this._isDirty = true;
  83557. this._meshesWithPoseMatrix = new Array();
  83558. this._identity = BABYLON.Matrix.Identity();
  83559. this._ranges = {};
  83560. this._lastAbsoluteTransformsUpdateId = -1;
  83561. /**
  83562. * Specifies if the skeleton should be serialized
  83563. */
  83564. this.doNotSerialize = false;
  83565. this._animationPropertiesOverride = null;
  83566. // Events
  83567. /**
  83568. * An observable triggered before computing the skeleton's matrices
  83569. */
  83570. this.onBeforeComputeObservable = new BABYLON.Observable();
  83571. this.bones = [];
  83572. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83573. scene.skeletons.push(this);
  83574. //make sure it will recalculate the matrix next time prepare is called.
  83575. this._isDirty = true;
  83576. }
  83577. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  83578. /**
  83579. * Gets or sets the animation properties override
  83580. */
  83581. get: function () {
  83582. if (!this._animationPropertiesOverride) {
  83583. return this._scene.animationPropertiesOverride;
  83584. }
  83585. return this._animationPropertiesOverride;
  83586. },
  83587. set: function (value) {
  83588. this._animationPropertiesOverride = value;
  83589. },
  83590. enumerable: true,
  83591. configurable: true
  83592. });
  83593. // Members
  83594. /**
  83595. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  83596. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  83597. * @returns a Float32Array containing matrices data
  83598. */
  83599. Skeleton.prototype.getTransformMatrices = function (mesh) {
  83600. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  83601. return mesh._bonesTransformMatrices;
  83602. }
  83603. if (!this._transformMatrices) {
  83604. this.prepare();
  83605. }
  83606. return this._transformMatrices;
  83607. };
  83608. /**
  83609. * Gets the current hosting scene
  83610. * @returns a scene object
  83611. */
  83612. Skeleton.prototype.getScene = function () {
  83613. return this._scene;
  83614. };
  83615. // Methods
  83616. /**
  83617. * Gets a string representing the current skeleton data
  83618. * @param fullDetails defines a boolean indicating if we want a verbose version
  83619. * @returns a string representing the current skeleton data
  83620. */
  83621. Skeleton.prototype.toString = function (fullDetails) {
  83622. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  83623. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  83624. if (fullDetails) {
  83625. ret += ", Ranges: {";
  83626. var first = true;
  83627. for (var name_1 in this._ranges) {
  83628. if (first) {
  83629. ret += ", ";
  83630. first = false;
  83631. }
  83632. ret += name_1;
  83633. }
  83634. ret += "}";
  83635. }
  83636. return ret;
  83637. };
  83638. /**
  83639. * Get bone's index searching by name
  83640. * @param name defines bone's name to search for
  83641. * @return the indice of the bone. Returns -1 if not found
  83642. */
  83643. Skeleton.prototype.getBoneIndexByName = function (name) {
  83644. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  83645. if (this.bones[boneIndex].name === name) {
  83646. return boneIndex;
  83647. }
  83648. }
  83649. return -1;
  83650. };
  83651. /**
  83652. * Creater a new animation range
  83653. * @param name defines the name of the range
  83654. * @param from defines the start key
  83655. * @param to defines the end key
  83656. */
  83657. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  83658. // check name not already in use
  83659. if (!this._ranges[name]) {
  83660. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  83661. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83662. if (this.bones[i].animations[0]) {
  83663. this.bones[i].animations[0].createRange(name, from, to);
  83664. }
  83665. }
  83666. }
  83667. };
  83668. /**
  83669. * Delete a specific animation range
  83670. * @param name defines the name of the range
  83671. * @param deleteFrames defines if frames must be removed as well
  83672. */
  83673. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  83674. if (deleteFrames === void 0) { deleteFrames = true; }
  83675. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83676. if (this.bones[i].animations[0]) {
  83677. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  83678. }
  83679. }
  83680. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  83681. };
  83682. /**
  83683. * Gets a specific animation range
  83684. * @param name defines the name of the range to look for
  83685. * @returns the requested animation range or null if not found
  83686. */
  83687. Skeleton.prototype.getAnimationRange = function (name) {
  83688. return this._ranges[name];
  83689. };
  83690. /**
  83691. * Gets the list of all animation ranges defined on this skeleton
  83692. * @returns an array
  83693. */
  83694. Skeleton.prototype.getAnimationRanges = function () {
  83695. var animationRanges = [];
  83696. var name;
  83697. var i = 0;
  83698. for (name in this._ranges) {
  83699. animationRanges[i] = this._ranges[name];
  83700. i++;
  83701. }
  83702. return animationRanges;
  83703. };
  83704. /**
  83705. * Copy animation range from a source skeleton.
  83706. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  83707. * @param source defines the source skeleton
  83708. * @param name defines the name of the range to copy
  83709. * @param rescaleAsRequired defines if rescaling must be applied if required
  83710. * @returns true if operation was successful
  83711. */
  83712. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  83713. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  83714. if (this._ranges[name] || !source.getAnimationRange(name)) {
  83715. return false;
  83716. }
  83717. var ret = true;
  83718. var frameOffset = this._getHighestAnimationFrame() + 1;
  83719. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  83720. var boneDict = {};
  83721. var sourceBones = source.bones;
  83722. var nBones;
  83723. var i;
  83724. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  83725. boneDict[sourceBones[i].name] = sourceBones[i];
  83726. }
  83727. if (this.bones.length !== sourceBones.length) {
  83728. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  83729. ret = false;
  83730. }
  83731. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  83732. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  83733. var boneName = this.bones[i].name;
  83734. var sourceBone = boneDict[boneName];
  83735. if (sourceBone) {
  83736. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  83737. }
  83738. else {
  83739. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  83740. ret = false;
  83741. }
  83742. }
  83743. // do not call createAnimationRange(), since it also is done to bones, which was already done
  83744. var range = source.getAnimationRange(name);
  83745. if (range) {
  83746. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  83747. }
  83748. return ret;
  83749. };
  83750. /**
  83751. * Forces the skeleton to go to rest pose
  83752. */
  83753. Skeleton.prototype.returnToRest = function () {
  83754. for (var index = 0; index < this.bones.length; index++) {
  83755. this.bones[index].returnToRest();
  83756. }
  83757. };
  83758. Skeleton.prototype._getHighestAnimationFrame = function () {
  83759. var ret = 0;
  83760. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83761. if (this.bones[i].animations[0]) {
  83762. var highest = this.bones[i].animations[0].getHighestFrame();
  83763. if (ret < highest) {
  83764. ret = highest;
  83765. }
  83766. }
  83767. }
  83768. return ret;
  83769. };
  83770. /**
  83771. * Begin a specific animation range
  83772. * @param name defines the name of the range to start
  83773. * @param loop defines if looping must be turned on (false by default)
  83774. * @param speedRatio defines the speed ratio to apply (1 by default)
  83775. * @param onAnimationEnd defines a callback which will be called when animation will end
  83776. * @returns a new animatable
  83777. */
  83778. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  83779. var range = this.getAnimationRange(name);
  83780. if (!range) {
  83781. return null;
  83782. }
  83783. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  83784. };
  83785. /** @hidden */
  83786. Skeleton.prototype._markAsDirty = function () {
  83787. this._isDirty = true;
  83788. };
  83789. /** @hidden */
  83790. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  83791. this._meshesWithPoseMatrix.push(mesh);
  83792. };
  83793. /** @hidden */
  83794. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  83795. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  83796. if (index > -1) {
  83797. this._meshesWithPoseMatrix.splice(index, 1);
  83798. }
  83799. };
  83800. /** @hidden */
  83801. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  83802. this.onBeforeComputeObservable.notifyObservers(this);
  83803. for (var index = 0; index < this.bones.length; index++) {
  83804. var bone = this.bones[index];
  83805. var parentBone = bone.getParent();
  83806. if (parentBone) {
  83807. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  83808. }
  83809. else {
  83810. if (initialSkinMatrix) {
  83811. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  83812. }
  83813. else {
  83814. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  83815. }
  83816. }
  83817. if (bone._index !== -1) {
  83818. var mappedIndex = bone._index === null ? index : bone._index;
  83819. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  83820. }
  83821. }
  83822. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  83823. };
  83824. /**
  83825. * Build all resources required to render a skeleton
  83826. */
  83827. Skeleton.prototype.prepare = function () {
  83828. if (!this._isDirty) {
  83829. return;
  83830. }
  83831. if (this.needInitialSkinMatrix) {
  83832. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  83833. var mesh = this._meshesWithPoseMatrix[index];
  83834. var poseMatrix = mesh.getPoseMatrix();
  83835. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  83836. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  83837. }
  83838. if (this._synchronizedWithMesh !== mesh) {
  83839. this._synchronizedWithMesh = mesh;
  83840. // Prepare bones
  83841. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  83842. var bone = this.bones[boneIndex];
  83843. if (!bone.getParent()) {
  83844. var matrix = bone.getBaseMatrix();
  83845. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  83846. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  83847. }
  83848. }
  83849. }
  83850. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  83851. }
  83852. }
  83853. else {
  83854. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  83855. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  83856. }
  83857. this._computeTransformMatrices(this._transformMatrices, null);
  83858. }
  83859. this._isDirty = false;
  83860. this._scene._activeBones.addCount(this.bones.length, false);
  83861. };
  83862. /**
  83863. * Gets the list of animatables currently running for this skeleton
  83864. * @returns an array of animatables
  83865. */
  83866. Skeleton.prototype.getAnimatables = function () {
  83867. if (!this._animatables || this._animatables.length !== this.bones.length) {
  83868. this._animatables = [];
  83869. for (var index = 0; index < this.bones.length; index++) {
  83870. this._animatables.push(this.bones[index]);
  83871. }
  83872. }
  83873. return this._animatables;
  83874. };
  83875. /**
  83876. * Clone the current skeleton
  83877. * @param name defines the name of the new skeleton
  83878. * @param id defines the id of the enw skeleton
  83879. * @returns the new skeleton
  83880. */
  83881. Skeleton.prototype.clone = function (name, id) {
  83882. var result = new Skeleton(name, id || name, this._scene);
  83883. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  83884. for (var index = 0; index < this.bones.length; index++) {
  83885. var source = this.bones[index];
  83886. var parentBone = null;
  83887. var parent_1 = source.getParent();
  83888. if (parent_1) {
  83889. var parentIndex = this.bones.indexOf(parent_1);
  83890. parentBone = result.bones[parentIndex];
  83891. }
  83892. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  83893. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  83894. }
  83895. if (this._ranges) {
  83896. result._ranges = {};
  83897. for (var rangeName in this._ranges) {
  83898. var range = this._ranges[rangeName];
  83899. if (range) {
  83900. result._ranges[rangeName] = range.clone();
  83901. }
  83902. }
  83903. }
  83904. this._isDirty = true;
  83905. return result;
  83906. };
  83907. /**
  83908. * Enable animation blending for this skeleton
  83909. * @param blendingSpeed defines the blending speed to apply
  83910. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  83911. */
  83912. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  83913. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  83914. this.bones.forEach(function (bone) {
  83915. bone.animations.forEach(function (animation) {
  83916. animation.enableBlending = true;
  83917. animation.blendingSpeed = blendingSpeed;
  83918. });
  83919. });
  83920. };
  83921. /**
  83922. * Releases all resources associated with the current skeleton
  83923. */
  83924. Skeleton.prototype.dispose = function () {
  83925. this._meshesWithPoseMatrix = [];
  83926. // Animations
  83927. this.getScene().stopAnimation(this);
  83928. // Remove from scene
  83929. this.getScene().removeSkeleton(this);
  83930. };
  83931. /**
  83932. * Serialize the skeleton in a JSON object
  83933. * @returns a JSON object
  83934. */
  83935. Skeleton.prototype.serialize = function () {
  83936. var serializationObject = {};
  83937. serializationObject.name = this.name;
  83938. serializationObject.id = this.id;
  83939. if (this.dimensionsAtRest) {
  83940. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  83941. }
  83942. serializationObject.bones = [];
  83943. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  83944. for (var index = 0; index < this.bones.length; index++) {
  83945. var bone = this.bones[index];
  83946. var parent_2 = bone.getParent();
  83947. var serializedBone = {
  83948. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  83949. name: bone.name,
  83950. matrix: bone.getBaseMatrix().toArray(),
  83951. rest: bone.getRestPose().toArray()
  83952. };
  83953. serializationObject.bones.push(serializedBone);
  83954. if (bone.length) {
  83955. serializedBone.length = bone.length;
  83956. }
  83957. if (bone.metadata) {
  83958. serializedBone.metadata = bone.metadata;
  83959. }
  83960. if (bone.animations && bone.animations.length > 0) {
  83961. serializedBone.animation = bone.animations[0].serialize();
  83962. }
  83963. serializationObject.ranges = [];
  83964. for (var name in this._ranges) {
  83965. var source = this._ranges[name];
  83966. if (!source) {
  83967. continue;
  83968. }
  83969. var range = {};
  83970. range.name = name;
  83971. range.from = source.from;
  83972. range.to = source.to;
  83973. serializationObject.ranges.push(range);
  83974. }
  83975. }
  83976. return serializationObject;
  83977. };
  83978. /**
  83979. * Creates a new skeleton from serialized data
  83980. * @param parsedSkeleton defines the serialized data
  83981. * @param scene defines the hosting scene
  83982. * @returns a new skeleton
  83983. */
  83984. Skeleton.Parse = function (parsedSkeleton, scene) {
  83985. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  83986. if (parsedSkeleton.dimensionsAtRest) {
  83987. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  83988. }
  83989. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  83990. var index;
  83991. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  83992. var parsedBone = parsedSkeleton.bones[index];
  83993. var parentBone = null;
  83994. if (parsedBone.parentBoneIndex > -1) {
  83995. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  83996. }
  83997. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  83998. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  83999. if (parsedBone.length) {
  84000. bone.length = parsedBone.length;
  84001. }
  84002. if (parsedBone.metadata) {
  84003. bone.metadata = parsedBone.metadata;
  84004. }
  84005. if (parsedBone.animation) {
  84006. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  84007. }
  84008. }
  84009. // placed after bones, so createAnimationRange can cascade down
  84010. if (parsedSkeleton.ranges) {
  84011. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  84012. var data = parsedSkeleton.ranges[index];
  84013. skeleton.createAnimationRange(data.name, data.from, data.to);
  84014. }
  84015. }
  84016. return skeleton;
  84017. };
  84018. /**
  84019. * Compute all node absolute transforms
  84020. * @param forceUpdate defines if computation must be done even if cache is up to date
  84021. */
  84022. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  84023. if (forceUpdate === void 0) { forceUpdate = false; }
  84024. var renderId = this._scene.getRenderId();
  84025. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  84026. this.bones[0].computeAbsoluteTransforms();
  84027. this._lastAbsoluteTransformsUpdateId = renderId;
  84028. }
  84029. };
  84030. /**
  84031. * Gets the root pose matrix
  84032. * @returns a matrix
  84033. */
  84034. Skeleton.prototype.getPoseMatrix = function () {
  84035. var poseMatrix = null;
  84036. if (this._meshesWithPoseMatrix.length > 0) {
  84037. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  84038. }
  84039. return poseMatrix;
  84040. };
  84041. /**
  84042. * Sorts bones per internal index
  84043. */
  84044. Skeleton.prototype.sortBones = function () {
  84045. var bones = new Array();
  84046. var visited = new Array(this.bones.length);
  84047. for (var index = 0; index < this.bones.length; index++) {
  84048. this._sortBones(index, bones, visited);
  84049. }
  84050. this.bones = bones;
  84051. };
  84052. Skeleton.prototype._sortBones = function (index, bones, visited) {
  84053. if (visited[index]) {
  84054. return;
  84055. }
  84056. visited[index] = true;
  84057. var bone = this.bones[index];
  84058. if (bone._index === undefined) {
  84059. bone._index = index;
  84060. }
  84061. var parentBone = bone.getParent();
  84062. if (parentBone) {
  84063. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  84064. }
  84065. bones.push(bone);
  84066. };
  84067. return Skeleton;
  84068. }());
  84069. BABYLON.Skeleton = Skeleton;
  84070. })(BABYLON || (BABYLON = {}));
  84071. //# sourceMappingURL=babylon.skeleton.js.map
  84072. var BABYLON;
  84073. (function (BABYLON) {
  84074. ;
  84075. /**
  84076. * This groups tools to convert HDR texture to native colors array.
  84077. */
  84078. var HDRTools = /** @class */ (function () {
  84079. function HDRTools() {
  84080. }
  84081. HDRTools.Ldexp = function (mantissa, exponent) {
  84082. if (exponent > 1023) {
  84083. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  84084. }
  84085. if (exponent < -1074) {
  84086. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  84087. }
  84088. return mantissa * Math.pow(2, exponent);
  84089. };
  84090. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  84091. if (exponent > 0) { /*nonzero pixel*/
  84092. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  84093. float32array[index + 0] = red * exponent;
  84094. float32array[index + 1] = green * exponent;
  84095. float32array[index + 2] = blue * exponent;
  84096. }
  84097. else {
  84098. float32array[index + 0] = 0;
  84099. float32array[index + 1] = 0;
  84100. float32array[index + 2] = 0;
  84101. }
  84102. };
  84103. HDRTools.readStringLine = function (uint8array, startIndex) {
  84104. var line = "";
  84105. var character = "";
  84106. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  84107. character = String.fromCharCode(uint8array[i]);
  84108. if (character == "\n") {
  84109. break;
  84110. }
  84111. line += character;
  84112. }
  84113. return line;
  84114. };
  84115. /**
  84116. * Reads header information from an RGBE texture stored in a native array.
  84117. * More information on this format are available here:
  84118. * https://en.wikipedia.org/wiki/RGBE_image_format
  84119. *
  84120. * @param uint8array The binary file stored in native array.
  84121. * @return The header information.
  84122. */
  84123. HDRTools.RGBE_ReadHeader = function (uint8array) {
  84124. var height = 0;
  84125. var width = 0;
  84126. var line = this.readStringLine(uint8array, 0);
  84127. if (line[0] != '#' || line[1] != '?') {
  84128. throw "Bad HDR Format.";
  84129. }
  84130. var endOfHeader = false;
  84131. var findFormat = false;
  84132. var lineIndex = 0;
  84133. do {
  84134. lineIndex += (line.length + 1);
  84135. line = this.readStringLine(uint8array, lineIndex);
  84136. if (line == "FORMAT=32-bit_rle_rgbe") {
  84137. findFormat = true;
  84138. }
  84139. else if (line.length == 0) {
  84140. endOfHeader = true;
  84141. }
  84142. } while (!endOfHeader);
  84143. if (!findFormat) {
  84144. throw "HDR Bad header format, unsupported FORMAT";
  84145. }
  84146. lineIndex += (line.length + 1);
  84147. line = this.readStringLine(uint8array, lineIndex);
  84148. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  84149. var match = sizeRegexp.exec(line);
  84150. // TODO. Support +Y and -X if needed.
  84151. if (!match || match.length < 3) {
  84152. throw "HDR Bad header format, no size";
  84153. }
  84154. width = parseInt(match[2]);
  84155. height = parseInt(match[1]);
  84156. if (width < 8 || width > 0x7fff) {
  84157. throw "HDR Bad header format, unsupported size";
  84158. }
  84159. lineIndex += (line.length + 1);
  84160. return {
  84161. height: height,
  84162. width: width,
  84163. dataPosition: lineIndex
  84164. };
  84165. };
  84166. /**
  84167. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  84168. * This RGBE texture needs to store the information as a panorama.
  84169. *
  84170. * More information on this format are available here:
  84171. * https://en.wikipedia.org/wiki/RGBE_image_format
  84172. *
  84173. * @param buffer The binary file stored in an array buffer.
  84174. * @param size The expected size of the extracted cubemap.
  84175. * @return The Cube Map information.
  84176. */
  84177. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  84178. var uint8array = new Uint8Array(buffer);
  84179. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  84180. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  84181. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  84182. return cubeMapData;
  84183. };
  84184. /**
  84185. * Returns the pixels data extracted from an RGBE texture.
  84186. * This pixels will be stored left to right up to down in the R G B order in one array.
  84187. *
  84188. * More information on this format are available here:
  84189. * https://en.wikipedia.org/wiki/RGBE_image_format
  84190. *
  84191. * @param uint8array The binary file stored in an array buffer.
  84192. * @param hdrInfo The header information of the file.
  84193. * @return The pixels data in RGB right to left up to down order.
  84194. */
  84195. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  84196. // Keep for multi format supports.
  84197. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  84198. };
  84199. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  84200. var num_scanlines = hdrInfo.height;
  84201. var scanline_width = hdrInfo.width;
  84202. var a, b, c, d, count;
  84203. var dataIndex = hdrInfo.dataPosition;
  84204. var index = 0, endIndex = 0, i = 0;
  84205. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  84206. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  84207. // 3 channels of 4 bytes per pixel in float.
  84208. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  84209. var resultArray = new Float32Array(resultBuffer);
  84210. // read in each successive scanline
  84211. while (num_scanlines > 0) {
  84212. a = uint8array[dataIndex++];
  84213. b = uint8array[dataIndex++];
  84214. c = uint8array[dataIndex++];
  84215. d = uint8array[dataIndex++];
  84216. if (a != 2 || b != 2 || (c & 0x80)) {
  84217. // this file is not run length encoded
  84218. throw "HDR Bad header format, not RLE";
  84219. }
  84220. if (((c << 8) | d) != scanline_width) {
  84221. throw "HDR Bad header format, wrong scan line width";
  84222. }
  84223. index = 0;
  84224. // read each of the four channels for the scanline into the buffer
  84225. for (i = 0; i < 4; i++) {
  84226. endIndex = (i + 1) * scanline_width;
  84227. while (index < endIndex) {
  84228. a = uint8array[dataIndex++];
  84229. b = uint8array[dataIndex++];
  84230. if (a > 128) {
  84231. // a run of the same value
  84232. count = a - 128;
  84233. if ((count == 0) || (count > endIndex - index)) {
  84234. throw "HDR Bad Format, bad scanline data (run)";
  84235. }
  84236. while (count-- > 0) {
  84237. scanLineArray[index++] = b;
  84238. }
  84239. }
  84240. else {
  84241. // a non-run
  84242. count = a;
  84243. if ((count == 0) || (count > endIndex - index)) {
  84244. throw "HDR Bad Format, bad scanline data (non-run)";
  84245. }
  84246. scanLineArray[index++] = b;
  84247. if (--count > 0) {
  84248. for (var j = 0; j < count; j++) {
  84249. scanLineArray[index++] = uint8array[dataIndex++];
  84250. }
  84251. }
  84252. }
  84253. }
  84254. }
  84255. // now convert data from buffer into floats
  84256. for (i = 0; i < scanline_width; i++) {
  84257. a = scanLineArray[i];
  84258. b = scanLineArray[i + scanline_width];
  84259. c = scanLineArray[i + 2 * scanline_width];
  84260. d = scanLineArray[i + 3 * scanline_width];
  84261. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  84262. }
  84263. num_scanlines--;
  84264. }
  84265. return resultArray;
  84266. };
  84267. return HDRTools;
  84268. }());
  84269. BABYLON.HDRTools = HDRTools;
  84270. })(BABYLON || (BABYLON = {}));
  84271. //# sourceMappingURL=babylon.hdr.js.map
  84272. var BABYLON;
  84273. (function (BABYLON) {
  84274. /**
  84275. * This represents a texture coming from an HDR input.
  84276. *
  84277. * The only supported format is currently panorama picture stored in RGBE format.
  84278. * Example of such files can be found on HDRLib: http://hdrlib.com/
  84279. */
  84280. var HDRCubeTexture = /** @class */ (function (_super) {
  84281. __extends(HDRCubeTexture, _super);
  84282. /**
  84283. * Instantiates an HDRTexture from the following parameters.
  84284. *
  84285. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  84286. * @param scene The scene the texture will be used in
  84287. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  84288. * @param noMipmap Forces to not generate the mipmap if true
  84289. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  84290. * @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)
  84291. * @param reserved Reserved flag for internal use.
  84292. */
  84293. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  84294. if (noMipmap === void 0) { noMipmap = false; }
  84295. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84296. if (gammaSpace === void 0) { gammaSpace = false; }
  84297. if (reserved === void 0) { reserved = false; }
  84298. if (onLoad === void 0) { onLoad = null; }
  84299. if (onError === void 0) { onError = null; }
  84300. var _this = _super.call(this, scene) || this;
  84301. _this._generateHarmonics = true;
  84302. _this._onLoad = null;
  84303. _this._onError = null;
  84304. /**
  84305. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  84306. */
  84307. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  84308. _this._isBlocking = true;
  84309. _this._rotationY = 0;
  84310. /**
  84311. * Gets or sets the center of the bounding box associated with the cube texture
  84312. * It must define where the camera used to render the texture was set
  84313. */
  84314. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  84315. if (!url) {
  84316. return _this;
  84317. }
  84318. _this.name = url;
  84319. _this.url = url;
  84320. _this.hasAlpha = false;
  84321. _this.isCube = true;
  84322. _this._textureMatrix = BABYLON.Matrix.Identity();
  84323. _this._onLoad = onLoad;
  84324. _this._onError = onError;
  84325. _this.gammaSpace = gammaSpace;
  84326. _this._noMipmap = noMipmap;
  84327. _this._size = size;
  84328. _this._texture = _this._getFromCache(url, _this._noMipmap);
  84329. if (!_this._texture) {
  84330. if (!scene.useDelayedTextureLoading) {
  84331. _this.loadTexture();
  84332. }
  84333. else {
  84334. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  84335. }
  84336. }
  84337. return _this;
  84338. }
  84339. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  84340. /**
  84341. * Gets wether or not the texture is blocking during loading.
  84342. */
  84343. get: function () {
  84344. return this._isBlocking;
  84345. },
  84346. /**
  84347. * Sets wether or not the texture is blocking during loading.
  84348. */
  84349. set: function (value) {
  84350. this._isBlocking = value;
  84351. },
  84352. enumerable: true,
  84353. configurable: true
  84354. });
  84355. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  84356. /**
  84357. * Gets texture matrix rotation angle around Y axis radians.
  84358. */
  84359. get: function () {
  84360. return this._rotationY;
  84361. },
  84362. /**
  84363. * Sets texture matrix rotation angle around Y axis in radians.
  84364. */
  84365. set: function (value) {
  84366. this._rotationY = value;
  84367. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  84368. },
  84369. enumerable: true,
  84370. configurable: true
  84371. });
  84372. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  84373. get: function () {
  84374. return this._boundingBoxSize;
  84375. },
  84376. /**
  84377. * Gets or sets the size of the bounding box associated with the cube texture
  84378. * When defined, the cubemap will switch to local mode
  84379. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  84380. * @example https://www.babylonjs-playground.com/#RNASML
  84381. */
  84382. set: function (value) {
  84383. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  84384. return;
  84385. }
  84386. this._boundingBoxSize = value;
  84387. var scene = this.getScene();
  84388. if (scene) {
  84389. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  84390. }
  84391. },
  84392. enumerable: true,
  84393. configurable: true
  84394. });
  84395. /**
  84396. * Occurs when the file is raw .hdr file.
  84397. */
  84398. HDRCubeTexture.prototype.loadTexture = function () {
  84399. var _this = this;
  84400. var callback = function (buffer) {
  84401. _this.lodGenerationOffset = 0.0;
  84402. _this.lodGenerationScale = 0.8;
  84403. var scene = _this.getScene();
  84404. if (!scene) {
  84405. return null;
  84406. }
  84407. // Extract the raw linear data.
  84408. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  84409. // Generate harmonics if needed.
  84410. if (_this._generateHarmonics) {
  84411. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  84412. _this.sphericalPolynomial = sphericalPolynomial;
  84413. }
  84414. var results = [];
  84415. var byteArray = null;
  84416. // Push each faces.
  84417. for (var j = 0; j < 6; j++) {
  84418. // Create uintarray fallback.
  84419. if (!scene.getEngine().getCaps().textureFloat) {
  84420. // 3 channels of 1 bytes per pixel in bytes.
  84421. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  84422. byteArray = new Uint8Array(byteBuffer);
  84423. }
  84424. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  84425. // If special cases.
  84426. if (_this.gammaSpace || byteArray) {
  84427. for (var i = 0; i < _this._size * _this._size; i++) {
  84428. // Put in gamma space if requested.
  84429. if (_this.gammaSpace) {
  84430. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  84431. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  84432. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  84433. }
  84434. // Convert to int texture for fallback.
  84435. if (byteArray) {
  84436. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  84437. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  84438. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  84439. // May use luminance instead if the result is not accurate.
  84440. var max = Math.max(Math.max(r, g), b);
  84441. if (max > 255) {
  84442. var scale = 255 / max;
  84443. r *= scale;
  84444. g *= scale;
  84445. b *= scale;
  84446. }
  84447. byteArray[(i * 3) + 0] = r;
  84448. byteArray[(i * 3) + 1] = g;
  84449. byteArray[(i * 3) + 2] = b;
  84450. }
  84451. }
  84452. }
  84453. if (byteArray) {
  84454. results.push(byteArray);
  84455. }
  84456. else {
  84457. results.push(dataFace);
  84458. }
  84459. }
  84460. return results;
  84461. };
  84462. var scene = this.getScene();
  84463. if (scene) {
  84464. 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);
  84465. }
  84466. };
  84467. HDRCubeTexture.prototype.clone = function () {
  84468. var scene = this.getScene();
  84469. if (!scene) {
  84470. return this;
  84471. }
  84472. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  84473. // Base texture
  84474. newTexture.level = this.level;
  84475. newTexture.wrapU = this.wrapU;
  84476. newTexture.wrapV = this.wrapV;
  84477. newTexture.coordinatesIndex = this.coordinatesIndex;
  84478. newTexture.coordinatesMode = this.coordinatesMode;
  84479. return newTexture;
  84480. };
  84481. // Methods
  84482. HDRCubeTexture.prototype.delayLoad = function () {
  84483. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  84484. return;
  84485. }
  84486. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  84487. this._texture = this._getFromCache(this.url, this._noMipmap);
  84488. if (!this._texture) {
  84489. this.loadTexture();
  84490. }
  84491. };
  84492. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  84493. return this._textureMatrix;
  84494. };
  84495. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  84496. this._textureMatrix = value;
  84497. };
  84498. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  84499. var texture = null;
  84500. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  84501. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  84502. texture.name = parsedTexture.name;
  84503. texture.hasAlpha = parsedTexture.hasAlpha;
  84504. texture.level = parsedTexture.level;
  84505. texture.coordinatesMode = parsedTexture.coordinatesMode;
  84506. texture.isBlocking = parsedTexture.isBlocking;
  84507. }
  84508. if (texture) {
  84509. if (parsedTexture.boundingBoxPosition) {
  84510. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  84511. }
  84512. if (parsedTexture.boundingBoxSize) {
  84513. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  84514. }
  84515. if (parsedTexture.rotationY) {
  84516. texture.rotationY = parsedTexture.rotationY;
  84517. }
  84518. }
  84519. return texture;
  84520. };
  84521. HDRCubeTexture.prototype.serialize = function () {
  84522. if (!this.name) {
  84523. return null;
  84524. }
  84525. var serializationObject = {};
  84526. serializationObject.name = this.name;
  84527. serializationObject.hasAlpha = this.hasAlpha;
  84528. serializationObject.isCube = true;
  84529. serializationObject.level = this.level;
  84530. serializationObject.size = this._size;
  84531. serializationObject.coordinatesMode = this.coordinatesMode;
  84532. serializationObject.useInGammaSpace = this.gammaSpace;
  84533. serializationObject.generateHarmonics = this._generateHarmonics;
  84534. serializationObject.customType = "BABYLON.HDRCubeTexture";
  84535. serializationObject.noMipmap = this._noMipmap;
  84536. serializationObject.isBlocking = this._isBlocking;
  84537. serializationObject.rotationY = this._rotationY;
  84538. return serializationObject;
  84539. };
  84540. HDRCubeTexture._facesMapping = [
  84541. "right",
  84542. "left",
  84543. "up",
  84544. "down",
  84545. "front",
  84546. "back"
  84547. ];
  84548. return HDRCubeTexture;
  84549. }(BABYLON.BaseTexture));
  84550. BABYLON.HDRCubeTexture = HDRCubeTexture;
  84551. })(BABYLON || (BABYLON = {}));
  84552. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  84553. var BABYLON;
  84554. (function (BABYLON) {
  84555. /**
  84556. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  84557. */
  84558. var PanoramaToCubeMapTools = /** @class */ (function () {
  84559. function PanoramaToCubeMapTools() {
  84560. }
  84561. /**
  84562. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  84563. *
  84564. * @param float32Array The source data.
  84565. * @param inputWidth The width of the input panorama.
  84566. * @param inputhHeight The height of the input panorama.
  84567. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  84568. * @return The cubemap data
  84569. */
  84570. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  84571. if (!float32Array) {
  84572. throw "ConvertPanoramaToCubemap: input cannot be null";
  84573. }
  84574. if (float32Array.length != inputWidth * inputHeight * 3) {
  84575. throw "ConvertPanoramaToCubemap: input size is wrong";
  84576. }
  84577. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  84578. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  84579. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  84580. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  84581. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  84582. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  84583. return {
  84584. front: textureFront,
  84585. back: textureBack,
  84586. left: textureLeft,
  84587. right: textureRight,
  84588. up: textureUp,
  84589. down: textureDown,
  84590. size: size,
  84591. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84592. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  84593. gammaSpace: false,
  84594. };
  84595. };
  84596. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  84597. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  84598. var textureArray = new Float32Array(buffer);
  84599. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  84600. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  84601. var dy = 1 / texSize;
  84602. var fy = 0;
  84603. for (var y = 0; y < texSize; y++) {
  84604. var xv1 = faceData[0];
  84605. var xv2 = faceData[2];
  84606. for (var x = 0; x < texSize; x++) {
  84607. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  84608. v.normalize();
  84609. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  84610. // 3 channels per pixels
  84611. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  84612. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  84613. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  84614. xv1 = xv1.add(rotDX1);
  84615. xv2 = xv2.add(rotDX2);
  84616. }
  84617. fy += dy;
  84618. }
  84619. return textureArray;
  84620. };
  84621. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  84622. var theta = Math.atan2(vDir.z, vDir.x);
  84623. var phi = Math.acos(vDir.y);
  84624. while (theta < -Math.PI)
  84625. theta += 2 * Math.PI;
  84626. while (theta > Math.PI)
  84627. theta -= 2 * Math.PI;
  84628. var dx = theta / Math.PI;
  84629. var dy = phi / Math.PI;
  84630. // recenter.
  84631. dx = dx * 0.5 + 0.5;
  84632. var px = Math.round(dx * inputWidth);
  84633. if (px < 0)
  84634. px = 0;
  84635. else if (px >= inputWidth)
  84636. px = inputWidth - 1;
  84637. var py = Math.round(dy * inputHeight);
  84638. if (py < 0)
  84639. py = 0;
  84640. else if (py >= inputHeight)
  84641. py = inputHeight - 1;
  84642. var inputY = (inputHeight - py - 1);
  84643. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  84644. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  84645. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  84646. return {
  84647. r: r,
  84648. g: g,
  84649. b: b
  84650. };
  84651. };
  84652. PanoramaToCubeMapTools.FACE_FRONT = [
  84653. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84654. new BABYLON.Vector3(1.0, -1.0, -1.0),
  84655. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  84656. new BABYLON.Vector3(1.0, 1.0, -1.0)
  84657. ];
  84658. PanoramaToCubeMapTools.FACE_BACK = [
  84659. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84660. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84661. new BABYLON.Vector3(1.0, 1.0, 1.0),
  84662. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  84663. ];
  84664. PanoramaToCubeMapTools.FACE_RIGHT = [
  84665. new BABYLON.Vector3(1.0, -1.0, -1.0),
  84666. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84667. new BABYLON.Vector3(1.0, 1.0, -1.0),
  84668. new BABYLON.Vector3(1.0, 1.0, 1.0)
  84669. ];
  84670. PanoramaToCubeMapTools.FACE_LEFT = [
  84671. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84672. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84673. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  84674. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  84675. ];
  84676. PanoramaToCubeMapTools.FACE_DOWN = [
  84677. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  84678. new BABYLON.Vector3(1.0, 1.0, -1.0),
  84679. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  84680. new BABYLON.Vector3(1.0, 1.0, 1.0)
  84681. ];
  84682. PanoramaToCubeMapTools.FACE_UP = [
  84683. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84684. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84685. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84686. new BABYLON.Vector3(1.0, -1.0, -1.0)
  84687. ];
  84688. return PanoramaToCubeMapTools;
  84689. }());
  84690. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  84691. })(BABYLON || (BABYLON = {}));
  84692. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  84693. var BABYLON;
  84694. (function (BABYLON) {
  84695. var IndexedVector2 = /** @class */ (function (_super) {
  84696. __extends(IndexedVector2, _super);
  84697. function IndexedVector2(original, index) {
  84698. var _this = _super.call(this, original.x, original.y) || this;
  84699. _this.index = index;
  84700. return _this;
  84701. }
  84702. return IndexedVector2;
  84703. }(BABYLON.Vector2));
  84704. var PolygonPoints = /** @class */ (function () {
  84705. function PolygonPoints() {
  84706. this.elements = new Array();
  84707. }
  84708. PolygonPoints.prototype.add = function (originalPoints) {
  84709. var _this = this;
  84710. var result = new Array();
  84711. originalPoints.forEach(function (point) {
  84712. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  84713. var newPoint = new IndexedVector2(point, _this.elements.length);
  84714. result.push(newPoint);
  84715. _this.elements.push(newPoint);
  84716. }
  84717. });
  84718. return result;
  84719. };
  84720. PolygonPoints.prototype.computeBounds = function () {
  84721. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84722. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  84723. this.elements.forEach(function (point) {
  84724. // x
  84725. if (point.x < lmin.x) {
  84726. lmin.x = point.x;
  84727. }
  84728. else if (point.x > lmax.x) {
  84729. lmax.x = point.x;
  84730. }
  84731. // y
  84732. if (point.y < lmin.y) {
  84733. lmin.y = point.y;
  84734. }
  84735. else if (point.y > lmax.y) {
  84736. lmax.y = point.y;
  84737. }
  84738. });
  84739. return {
  84740. min: lmin,
  84741. max: lmax,
  84742. width: lmax.x - lmin.x,
  84743. height: lmax.y - lmin.y
  84744. };
  84745. };
  84746. return PolygonPoints;
  84747. }());
  84748. var Polygon = /** @class */ (function () {
  84749. function Polygon() {
  84750. }
  84751. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  84752. return [
  84753. new BABYLON.Vector2(xmin, ymin),
  84754. new BABYLON.Vector2(xmax, ymin),
  84755. new BABYLON.Vector2(xmax, ymax),
  84756. new BABYLON.Vector2(xmin, ymax)
  84757. ];
  84758. };
  84759. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  84760. if (cx === void 0) { cx = 0; }
  84761. if (cy === void 0) { cy = 0; }
  84762. if (numberOfSides === void 0) { numberOfSides = 32; }
  84763. var result = new Array();
  84764. var angle = 0;
  84765. var increment = (Math.PI * 2) / numberOfSides;
  84766. for (var i = 0; i < numberOfSides; i++) {
  84767. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  84768. angle -= increment;
  84769. }
  84770. return result;
  84771. };
  84772. Polygon.Parse = function (input) {
  84773. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  84774. var i, result = [];
  84775. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  84776. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  84777. }
  84778. return result;
  84779. };
  84780. Polygon.StartingAt = function (x, y) {
  84781. return BABYLON.Path2.StartingAt(x, y);
  84782. };
  84783. return Polygon;
  84784. }());
  84785. BABYLON.Polygon = Polygon;
  84786. var PolygonMeshBuilder = /** @class */ (function () {
  84787. function PolygonMeshBuilder(name, contours, scene) {
  84788. this._points = new PolygonPoints();
  84789. this._outlinepoints = new PolygonPoints();
  84790. this._holes = new Array();
  84791. this._epoints = new Array();
  84792. this._eholes = new Array();
  84793. this._name = name;
  84794. this._scene = scene;
  84795. var points;
  84796. if (contours instanceof BABYLON.Path2) {
  84797. points = contours.getPoints();
  84798. }
  84799. else {
  84800. points = contours;
  84801. }
  84802. this._addToepoint(points);
  84803. this._points.add(points);
  84804. this._outlinepoints.add(points);
  84805. if (typeof earcut === 'undefined') {
  84806. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  84807. }
  84808. }
  84809. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  84810. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  84811. var p = points_1[_i];
  84812. this._epoints.push(p.x, p.y);
  84813. }
  84814. };
  84815. PolygonMeshBuilder.prototype.addHole = function (hole) {
  84816. this._points.add(hole);
  84817. var holepoints = new PolygonPoints();
  84818. holepoints.add(hole);
  84819. this._holes.push(holepoints);
  84820. this._eholes.push(this._epoints.length / 2);
  84821. this._addToepoint(hole);
  84822. return this;
  84823. };
  84824. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  84825. var _this = this;
  84826. if (updatable === void 0) { updatable = false; }
  84827. if (depth === void 0) { depth = 0; }
  84828. var result = new BABYLON.Mesh(this._name, this._scene);
  84829. var normals = new Array();
  84830. var positions = new Array();
  84831. var uvs = new Array();
  84832. var bounds = this._points.computeBounds();
  84833. this._points.elements.forEach(function (p) {
  84834. normals.push(0, 1.0, 0);
  84835. positions.push(p.x, 0, p.y);
  84836. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  84837. });
  84838. var indices = new Array();
  84839. var res = earcut(this._epoints, this._eholes, 2);
  84840. for (var i = 0; i < res.length; i++) {
  84841. indices.push(res[i]);
  84842. }
  84843. if (depth > 0) {
  84844. var positionscount = (positions.length / 3); //get the current pointcount
  84845. this._points.elements.forEach(function (p) {
  84846. normals.push(0, -1.0, 0);
  84847. positions.push(p.x, -depth, p.y);
  84848. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  84849. });
  84850. var totalCount = indices.length;
  84851. for (var i = 0; i < totalCount; i += 3) {
  84852. var i0 = indices[i + 0];
  84853. var i1 = indices[i + 1];
  84854. var i2 = indices[i + 2];
  84855. indices.push(i2 + positionscount);
  84856. indices.push(i1 + positionscount);
  84857. indices.push(i0 + positionscount);
  84858. }
  84859. //Add the sides
  84860. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  84861. this._holes.forEach(function (hole) {
  84862. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  84863. });
  84864. }
  84865. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  84866. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  84867. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  84868. result.setIndices(indices);
  84869. return result;
  84870. };
  84871. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  84872. var StartIndex = positions.length / 3;
  84873. var ulength = 0;
  84874. for (var i = 0; i < points.elements.length; i++) {
  84875. var p = points.elements[i];
  84876. var p1;
  84877. if ((i + 1) > points.elements.length - 1) {
  84878. p1 = points.elements[0];
  84879. }
  84880. else {
  84881. p1 = points.elements[i + 1];
  84882. }
  84883. positions.push(p.x, 0, p.y);
  84884. positions.push(p.x, -depth, p.y);
  84885. positions.push(p1.x, 0, p1.y);
  84886. positions.push(p1.x, -depth, p1.y);
  84887. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  84888. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  84889. var v3 = v2.subtract(v1);
  84890. var v4 = new BABYLON.Vector3(0, 1, 0);
  84891. var vn = BABYLON.Vector3.Cross(v3, v4);
  84892. vn = vn.normalize();
  84893. uvs.push(ulength / bounds.width, 0);
  84894. uvs.push(ulength / bounds.width, 1);
  84895. ulength += v3.length();
  84896. uvs.push((ulength / bounds.width), 0);
  84897. uvs.push((ulength / bounds.width), 1);
  84898. if (!flip) {
  84899. normals.push(-vn.x, -vn.y, -vn.z);
  84900. normals.push(-vn.x, -vn.y, -vn.z);
  84901. normals.push(-vn.x, -vn.y, -vn.z);
  84902. normals.push(-vn.x, -vn.y, -vn.z);
  84903. indices.push(StartIndex);
  84904. indices.push(StartIndex + 1);
  84905. indices.push(StartIndex + 2);
  84906. indices.push(StartIndex + 1);
  84907. indices.push(StartIndex + 3);
  84908. indices.push(StartIndex + 2);
  84909. }
  84910. else {
  84911. normals.push(vn.x, vn.y, vn.z);
  84912. normals.push(vn.x, vn.y, vn.z);
  84913. normals.push(vn.x, vn.y, vn.z);
  84914. normals.push(vn.x, vn.y, vn.z);
  84915. indices.push(StartIndex);
  84916. indices.push(StartIndex + 2);
  84917. indices.push(StartIndex + 1);
  84918. indices.push(StartIndex + 1);
  84919. indices.push(StartIndex + 2);
  84920. indices.push(StartIndex + 3);
  84921. }
  84922. StartIndex += 4;
  84923. }
  84924. ;
  84925. };
  84926. return PolygonMeshBuilder;
  84927. }());
  84928. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  84929. })(BABYLON || (BABYLON = {}));
  84930. //# sourceMappingURL=babylon.polygonMesh.js.map
  84931. var BABYLON;
  84932. (function (BABYLON) {
  84933. // Unique ID when we import meshes from Babylon to CSG
  84934. var currentCSGMeshId = 0;
  84935. // # class Vertex
  84936. // Represents a vertex of a polygon. Use your own vertex class instead of this
  84937. // one to provide additional features like texture coordinates and vertex
  84938. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  84939. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  84940. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  84941. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  84942. // is not used anywhere else.
  84943. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  84944. var Vertex = /** @class */ (function () {
  84945. function Vertex(pos, normal, uv) {
  84946. this.pos = pos;
  84947. this.normal = normal;
  84948. this.uv = uv;
  84949. }
  84950. Vertex.prototype.clone = function () {
  84951. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  84952. };
  84953. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  84954. // orientation of a polygon is flipped.
  84955. Vertex.prototype.flip = function () {
  84956. this.normal = this.normal.scale(-1);
  84957. };
  84958. // Create a new vertex between this vertex and `other` by linearly
  84959. // interpolating all properties using a parameter of `t`. Subclasses should
  84960. // override this to interpolate additional properties.
  84961. Vertex.prototype.interpolate = function (other, t) {
  84962. 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));
  84963. };
  84964. return Vertex;
  84965. }());
  84966. // # class Plane
  84967. // Represents a plane in 3D space.
  84968. var Plane = /** @class */ (function () {
  84969. function Plane(normal, w) {
  84970. this.normal = normal;
  84971. this.w = w;
  84972. }
  84973. Plane.FromPoints = function (a, b, c) {
  84974. var v0 = c.subtract(a);
  84975. var v1 = b.subtract(a);
  84976. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  84977. return null;
  84978. }
  84979. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  84980. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  84981. };
  84982. Plane.prototype.clone = function () {
  84983. return new Plane(this.normal.clone(), this.w);
  84984. };
  84985. Plane.prototype.flip = function () {
  84986. this.normal.scaleInPlace(-1);
  84987. this.w = -this.w;
  84988. };
  84989. // Split `polygon` by this plane if needed, then put the polygon or polygon
  84990. // fragments in the appropriate lists. Coplanar polygons go into either
  84991. // `coplanarFront` or `coplanarBack` depending on their orientation with
  84992. // respect to this plane. Polygons in front or in back of this plane go into
  84993. // either `front` or `back`.
  84994. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  84995. var COPLANAR = 0;
  84996. var FRONT = 1;
  84997. var BACK = 2;
  84998. var SPANNING = 3;
  84999. // Classify each point as well as the entire polygon into one of the above
  85000. // four classes.
  85001. var polygonType = 0;
  85002. var types = [];
  85003. var i;
  85004. var t;
  85005. for (i = 0; i < polygon.vertices.length; i++) {
  85006. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  85007. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  85008. polygonType |= type;
  85009. types.push(type);
  85010. }
  85011. // Put the polygon in the correct list, splitting it when necessary.
  85012. switch (polygonType) {
  85013. case COPLANAR:
  85014. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  85015. break;
  85016. case FRONT:
  85017. front.push(polygon);
  85018. break;
  85019. case BACK:
  85020. back.push(polygon);
  85021. break;
  85022. case SPANNING:
  85023. var f = [], b = [];
  85024. for (i = 0; i < polygon.vertices.length; i++) {
  85025. var j = (i + 1) % polygon.vertices.length;
  85026. var ti = types[i], tj = types[j];
  85027. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  85028. if (ti !== BACK)
  85029. f.push(vi);
  85030. if (ti !== FRONT)
  85031. b.push(ti !== BACK ? vi.clone() : vi);
  85032. if ((ti | tj) === SPANNING) {
  85033. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  85034. var v = vi.interpolate(vj, t);
  85035. f.push(v);
  85036. b.push(v.clone());
  85037. }
  85038. }
  85039. var poly;
  85040. if (f.length >= 3) {
  85041. poly = new Polygon(f, polygon.shared);
  85042. if (poly.plane)
  85043. front.push(poly);
  85044. }
  85045. if (b.length >= 3) {
  85046. poly = new Polygon(b, polygon.shared);
  85047. if (poly.plane)
  85048. back.push(poly);
  85049. }
  85050. break;
  85051. }
  85052. };
  85053. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  85054. // point is on the plane.
  85055. Plane.EPSILON = 1e-5;
  85056. return Plane;
  85057. }());
  85058. // # class Polygon
  85059. // Represents a convex polygon. The vertices used to initialize a polygon must
  85060. // be coplanar and form a convex loop.
  85061. //
  85062. // Each convex polygon has a `shared` property, which is shared between all
  85063. // polygons that are clones of each other or were split from the same polygon.
  85064. // This can be used to define per-polygon properties (such as surface color).
  85065. var Polygon = /** @class */ (function () {
  85066. function Polygon(vertices, shared) {
  85067. this.vertices = vertices;
  85068. this.shared = shared;
  85069. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  85070. }
  85071. Polygon.prototype.clone = function () {
  85072. var vertices = this.vertices.map(function (v) { return v.clone(); });
  85073. return new Polygon(vertices, this.shared);
  85074. };
  85075. Polygon.prototype.flip = function () {
  85076. this.vertices.reverse().map(function (v) { v.flip(); });
  85077. this.plane.flip();
  85078. };
  85079. return Polygon;
  85080. }());
  85081. // # class Node
  85082. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  85083. // by picking a polygon to split along. That polygon (and all other coplanar
  85084. // polygons) are added directly to that node and the other polygons are added to
  85085. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  85086. // no distinction between internal and leaf nodes.
  85087. var Node = /** @class */ (function () {
  85088. function Node(polygons) {
  85089. this.plane = null;
  85090. this.front = null;
  85091. this.back = null;
  85092. this.polygons = new Array();
  85093. if (polygons) {
  85094. this.build(polygons);
  85095. }
  85096. }
  85097. Node.prototype.clone = function () {
  85098. var node = new Node();
  85099. node.plane = this.plane && this.plane.clone();
  85100. node.front = this.front && this.front.clone();
  85101. node.back = this.back && this.back.clone();
  85102. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  85103. return node;
  85104. };
  85105. // Convert solid space to empty space and empty space to solid space.
  85106. Node.prototype.invert = function () {
  85107. for (var i = 0; i < this.polygons.length; i++) {
  85108. this.polygons[i].flip();
  85109. }
  85110. if (this.plane) {
  85111. this.plane.flip();
  85112. }
  85113. if (this.front) {
  85114. this.front.invert();
  85115. }
  85116. if (this.back) {
  85117. this.back.invert();
  85118. }
  85119. var temp = this.front;
  85120. this.front = this.back;
  85121. this.back = temp;
  85122. };
  85123. // Recursively remove all polygons in `polygons` that are inside this BSP
  85124. // tree.
  85125. Node.prototype.clipPolygons = function (polygons) {
  85126. if (!this.plane)
  85127. return polygons.slice();
  85128. var front = new Array(), back = new Array();
  85129. for (var i = 0; i < polygons.length; i++) {
  85130. this.plane.splitPolygon(polygons[i], front, back, front, back);
  85131. }
  85132. if (this.front) {
  85133. front = this.front.clipPolygons(front);
  85134. }
  85135. if (this.back) {
  85136. back = this.back.clipPolygons(back);
  85137. }
  85138. else {
  85139. back = [];
  85140. }
  85141. return front.concat(back);
  85142. };
  85143. // Remove all polygons in this BSP tree that are inside the other BSP tree
  85144. // `bsp`.
  85145. Node.prototype.clipTo = function (bsp) {
  85146. this.polygons = bsp.clipPolygons(this.polygons);
  85147. if (this.front)
  85148. this.front.clipTo(bsp);
  85149. if (this.back)
  85150. this.back.clipTo(bsp);
  85151. };
  85152. // Return a list of all polygons in this BSP tree.
  85153. Node.prototype.allPolygons = function () {
  85154. var polygons = this.polygons.slice();
  85155. if (this.front)
  85156. polygons = polygons.concat(this.front.allPolygons());
  85157. if (this.back)
  85158. polygons = polygons.concat(this.back.allPolygons());
  85159. return polygons;
  85160. };
  85161. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  85162. // new polygons are filtered down to the bottom of the tree and become new
  85163. // nodes there. Each set of polygons is partitioned using the first polygon
  85164. // (no heuristic is used to pick a good split).
  85165. Node.prototype.build = function (polygons) {
  85166. if (!polygons.length)
  85167. return;
  85168. if (!this.plane)
  85169. this.plane = polygons[0].plane.clone();
  85170. var front = new Array(), back = new Array();
  85171. for (var i = 0; i < polygons.length; i++) {
  85172. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  85173. }
  85174. if (front.length) {
  85175. if (!this.front)
  85176. this.front = new Node();
  85177. this.front.build(front);
  85178. }
  85179. if (back.length) {
  85180. if (!this.back)
  85181. this.back = new Node();
  85182. this.back.build(back);
  85183. }
  85184. };
  85185. return Node;
  85186. }());
  85187. var CSG = /** @class */ (function () {
  85188. function CSG() {
  85189. this.polygons = new Array();
  85190. }
  85191. // Convert BABYLON.Mesh to BABYLON.CSG
  85192. CSG.FromMesh = function (mesh) {
  85193. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  85194. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  85195. if (mesh instanceof BABYLON.Mesh) {
  85196. mesh.computeWorldMatrix(true);
  85197. matrix = mesh.getWorldMatrix();
  85198. meshPosition = mesh.position.clone();
  85199. meshRotation = mesh.rotation.clone();
  85200. if (mesh.rotationQuaternion) {
  85201. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  85202. }
  85203. meshScaling = mesh.scaling.clone();
  85204. }
  85205. else {
  85206. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  85207. }
  85208. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85209. var subMeshes = mesh.subMeshes;
  85210. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  85211. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  85212. vertices = [];
  85213. for (var j = 0; j < 3; j++) {
  85214. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  85215. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  85216. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  85217. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  85218. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  85219. vertex = new Vertex(position, normal, uv);
  85220. vertices.push(vertex);
  85221. }
  85222. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  85223. // To handle the case of degenerated triangle
  85224. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  85225. if (polygon.plane)
  85226. polygons.push(polygon);
  85227. }
  85228. }
  85229. var csg = CSG.FromPolygons(polygons);
  85230. csg.matrix = matrix;
  85231. csg.position = meshPosition;
  85232. csg.rotation = meshRotation;
  85233. csg.scaling = meshScaling;
  85234. csg.rotationQuaternion = meshRotationQuaternion;
  85235. currentCSGMeshId++;
  85236. return csg;
  85237. };
  85238. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  85239. CSG.FromPolygons = function (polygons) {
  85240. var csg = new CSG();
  85241. csg.polygons = polygons;
  85242. return csg;
  85243. };
  85244. CSG.prototype.clone = function () {
  85245. var csg = new CSG();
  85246. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  85247. csg.copyTransformAttributes(this);
  85248. return csg;
  85249. };
  85250. CSG.prototype.union = function (csg) {
  85251. var a = new Node(this.clone().polygons);
  85252. var b = new Node(csg.clone().polygons);
  85253. a.clipTo(b);
  85254. b.clipTo(a);
  85255. b.invert();
  85256. b.clipTo(a);
  85257. b.invert();
  85258. a.build(b.allPolygons());
  85259. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  85260. };
  85261. CSG.prototype.unionInPlace = function (csg) {
  85262. var a = new Node(this.polygons);
  85263. var b = new Node(csg.polygons);
  85264. a.clipTo(b);
  85265. b.clipTo(a);
  85266. b.invert();
  85267. b.clipTo(a);
  85268. b.invert();
  85269. a.build(b.allPolygons());
  85270. this.polygons = a.allPolygons();
  85271. };
  85272. CSG.prototype.subtract = function (csg) {
  85273. var a = new Node(this.clone().polygons);
  85274. var b = new Node(csg.clone().polygons);
  85275. a.invert();
  85276. a.clipTo(b);
  85277. b.clipTo(a);
  85278. b.invert();
  85279. b.clipTo(a);
  85280. b.invert();
  85281. a.build(b.allPolygons());
  85282. a.invert();
  85283. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  85284. };
  85285. CSG.prototype.subtractInPlace = function (csg) {
  85286. var a = new Node(this.polygons);
  85287. var b = new Node(csg.polygons);
  85288. a.invert();
  85289. a.clipTo(b);
  85290. b.clipTo(a);
  85291. b.invert();
  85292. b.clipTo(a);
  85293. b.invert();
  85294. a.build(b.allPolygons());
  85295. a.invert();
  85296. this.polygons = a.allPolygons();
  85297. };
  85298. CSG.prototype.intersect = function (csg) {
  85299. var a = new Node(this.clone().polygons);
  85300. var b = new Node(csg.clone().polygons);
  85301. a.invert();
  85302. b.clipTo(a);
  85303. b.invert();
  85304. a.clipTo(b);
  85305. b.clipTo(a);
  85306. a.build(b.allPolygons());
  85307. a.invert();
  85308. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  85309. };
  85310. CSG.prototype.intersectInPlace = function (csg) {
  85311. var a = new Node(this.polygons);
  85312. var b = new Node(csg.polygons);
  85313. a.invert();
  85314. b.clipTo(a);
  85315. b.invert();
  85316. a.clipTo(b);
  85317. b.clipTo(a);
  85318. a.build(b.allPolygons());
  85319. a.invert();
  85320. this.polygons = a.allPolygons();
  85321. };
  85322. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  85323. // not modified.
  85324. CSG.prototype.inverse = function () {
  85325. var csg = this.clone();
  85326. csg.inverseInPlace();
  85327. return csg;
  85328. };
  85329. CSG.prototype.inverseInPlace = function () {
  85330. this.polygons.map(function (p) { p.flip(); });
  85331. };
  85332. // This is used to keep meshes transformations so they can be restored
  85333. // when we build back a Babylon Mesh
  85334. // NB : All CSG operations are performed in world coordinates
  85335. CSG.prototype.copyTransformAttributes = function (csg) {
  85336. this.matrix = csg.matrix;
  85337. this.position = csg.position;
  85338. this.rotation = csg.rotation;
  85339. this.scaling = csg.scaling;
  85340. this.rotationQuaternion = csg.rotationQuaternion;
  85341. return this;
  85342. };
  85343. // Build Raw mesh from CSG
  85344. // Coordinates here are in world space
  85345. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  85346. var matrix = this.matrix.clone();
  85347. matrix.invert();
  85348. 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;
  85349. if (keepSubMeshes) {
  85350. // Sort Polygons, since subMeshes are indices range
  85351. polygons.sort(function (a, b) {
  85352. if (a.shared.meshId === b.shared.meshId) {
  85353. return a.shared.subMeshId - b.shared.subMeshId;
  85354. }
  85355. else {
  85356. return a.shared.meshId - b.shared.meshId;
  85357. }
  85358. });
  85359. }
  85360. for (var i = 0, il = polygons.length; i < il; i++) {
  85361. polygon = polygons[i];
  85362. // Building SubMeshes
  85363. if (!subMesh_dict[polygon.shared.meshId]) {
  85364. subMesh_dict[polygon.shared.meshId] = {};
  85365. }
  85366. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  85367. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  85368. indexStart: +Infinity,
  85369. indexEnd: -Infinity,
  85370. materialIndex: polygon.shared.materialIndex
  85371. };
  85372. }
  85373. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  85374. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  85375. polygonIndices[0] = 0;
  85376. polygonIndices[1] = j - 1;
  85377. polygonIndices[2] = j;
  85378. for (var k = 0; k < 3; k++) {
  85379. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  85380. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  85381. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  85382. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  85383. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  85384. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  85385. // Check if 2 points can be merged
  85386. if (!(typeof vertex_idx !== 'undefined' &&
  85387. normals[vertex_idx * 3] === localNormal.x &&
  85388. normals[vertex_idx * 3 + 1] === localNormal.y &&
  85389. normals[vertex_idx * 3 + 2] === localNormal.z &&
  85390. uvs[vertex_idx * 2] === uv.x &&
  85391. uvs[vertex_idx * 2 + 1] === uv.y)) {
  85392. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  85393. uvs.push(uv.x, uv.y);
  85394. normals.push(normal.x, normal.y, normal.z);
  85395. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  85396. }
  85397. indices.push(vertex_idx);
  85398. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  85399. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  85400. currentIndex++;
  85401. }
  85402. }
  85403. }
  85404. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  85405. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  85406. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  85407. mesh.setIndices(indices, null);
  85408. if (keepSubMeshes) {
  85409. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  85410. var materialIndexOffset = 0, materialMaxIndex;
  85411. mesh.subMeshes = new Array();
  85412. for (var m in subMesh_dict) {
  85413. materialMaxIndex = -1;
  85414. for (var sm in subMesh_dict[m]) {
  85415. subMesh_obj = subMesh_dict[m][sm];
  85416. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  85417. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  85418. }
  85419. materialIndexOffset += ++materialMaxIndex;
  85420. }
  85421. }
  85422. return mesh;
  85423. };
  85424. // Build Mesh from CSG taking material and transforms into account
  85425. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  85426. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  85427. mesh.material = material;
  85428. mesh.position.copyFrom(this.position);
  85429. mesh.rotation.copyFrom(this.rotation);
  85430. if (this.rotationQuaternion) {
  85431. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  85432. }
  85433. mesh.scaling.copyFrom(this.scaling);
  85434. mesh.computeWorldMatrix(true);
  85435. return mesh;
  85436. };
  85437. return CSG;
  85438. }());
  85439. BABYLON.CSG = CSG;
  85440. })(BABYLON || (BABYLON = {}));
  85441. //# sourceMappingURL=babylon.csg.js.map
  85442. var BABYLON;
  85443. (function (BABYLON) {
  85444. var LensFlare = /** @class */ (function () {
  85445. function LensFlare(size, position, color, imgUrl, system) {
  85446. this.size = size;
  85447. this.position = position;
  85448. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  85449. this.color = color || new BABYLON.Color3(1, 1, 1);
  85450. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  85451. this._system = system;
  85452. system.lensFlares.push(this);
  85453. }
  85454. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  85455. return new LensFlare(size, position, color, imgUrl, system);
  85456. };
  85457. LensFlare.prototype.dispose = function () {
  85458. if (this.texture) {
  85459. this.texture.dispose();
  85460. }
  85461. // Remove from scene
  85462. var index = this._system.lensFlares.indexOf(this);
  85463. this._system.lensFlares.splice(index, 1);
  85464. };
  85465. ;
  85466. return LensFlare;
  85467. }());
  85468. BABYLON.LensFlare = LensFlare;
  85469. })(BABYLON || (BABYLON = {}));
  85470. //# sourceMappingURL=babylon.lensFlare.js.map
  85471. var BABYLON;
  85472. (function (BABYLON) {
  85473. // Adds the parser to the scene parsers.
  85474. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  85475. // Lens flares
  85476. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  85477. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  85478. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  85479. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  85480. container.lensFlareSystems.push(lf);
  85481. }
  85482. }
  85483. });
  85484. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  85485. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  85486. if (this.lensFlareSystems[index].name === name) {
  85487. return this.lensFlareSystems[index];
  85488. }
  85489. }
  85490. return null;
  85491. };
  85492. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  85493. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  85494. if (this.lensFlareSystems[index].id === id) {
  85495. return this.lensFlareSystems[index];
  85496. }
  85497. }
  85498. return null;
  85499. };
  85500. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  85501. var index = this.lensFlareSystems.indexOf(toRemove);
  85502. if (index !== -1) {
  85503. this.lensFlareSystems.splice(index, 1);
  85504. }
  85505. return index;
  85506. };
  85507. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  85508. this.lensFlareSystems.push(newLensFlareSystem);
  85509. };
  85510. /**
  85511. * Defines the lens flare scene component responsible to manage any lens flares
  85512. * in a given scene.
  85513. */
  85514. var LensFlareSystemSceneComponent = /** @class */ (function () {
  85515. /**
  85516. * Creates a new instance of the component for the given scene
  85517. * @param scene Defines the scene to register the component in
  85518. */
  85519. function LensFlareSystemSceneComponent(scene) {
  85520. /**
  85521. * The component name helpfull to identify the component in the list of scene components.
  85522. */
  85523. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  85524. this.scene = scene;
  85525. scene.lensFlareSystems = new Array();
  85526. }
  85527. /**
  85528. * Registers the component in a given scene
  85529. */
  85530. LensFlareSystemSceneComponent.prototype.register = function () {
  85531. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  85532. };
  85533. /**
  85534. * Rebuilds the elements related to this component in case of
  85535. * context lost for instance.
  85536. */
  85537. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  85538. // Nothing to do for lens flare
  85539. };
  85540. /**
  85541. * Adds all the element from the container to the scene
  85542. * @param container the container holding the elements
  85543. */
  85544. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  85545. var _this = this;
  85546. if (!container.lensFlareSystems) {
  85547. return;
  85548. }
  85549. container.lensFlareSystems.forEach(function (o) {
  85550. _this.scene.addLensFlareSystem(o);
  85551. });
  85552. };
  85553. /**
  85554. * Removes all the elements in the container from the scene
  85555. * @param container contains the elements to remove
  85556. */
  85557. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  85558. var _this = this;
  85559. if (!container.lensFlareSystems) {
  85560. return;
  85561. }
  85562. container.lensFlareSystems.forEach(function (o) {
  85563. _this.scene.removeLensFlareSystem(o);
  85564. });
  85565. };
  85566. /**
  85567. * Serializes the component data to the specified json object
  85568. * @param serializationObject The object to serialize to
  85569. */
  85570. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  85571. // Lens flares
  85572. serializationObject.lensFlareSystems = [];
  85573. var lensFlareSystems = this.scene.lensFlareSystems;
  85574. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  85575. var lensFlareSystem = lensFlareSystems_1[_i];
  85576. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  85577. }
  85578. };
  85579. /**
  85580. * Disposes the component and the associated ressources.
  85581. */
  85582. LensFlareSystemSceneComponent.prototype.dispose = function () {
  85583. var lensFlareSystems = this.scene.lensFlareSystems;
  85584. while (lensFlareSystems.length) {
  85585. lensFlareSystems[0].dispose();
  85586. }
  85587. };
  85588. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  85589. // Lens flares
  85590. if (this.scene.lensFlaresEnabled) {
  85591. var lensFlareSystems = this.scene.lensFlareSystems;
  85592. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85593. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  85594. var lensFlareSystem = lensFlareSystems_2[_i];
  85595. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  85596. lensFlareSystem.render();
  85597. }
  85598. }
  85599. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85600. }
  85601. };
  85602. return LensFlareSystemSceneComponent;
  85603. }());
  85604. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  85605. })(BABYLON || (BABYLON = {}));
  85606. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  85607. var BABYLON;
  85608. (function (BABYLON) {
  85609. var LensFlareSystem = /** @class */ (function () {
  85610. function LensFlareSystem(name, emitter, scene) {
  85611. this.name = name;
  85612. this.lensFlares = new Array();
  85613. this.borderLimit = 300;
  85614. this.viewportBorder = 0;
  85615. this.layerMask = 0x0FFFFFFF;
  85616. this._vertexBuffers = {};
  85617. this._isEnabled = true;
  85618. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85619. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  85620. if (!component) {
  85621. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  85622. scene._addComponent(component);
  85623. }
  85624. this._emitter = emitter;
  85625. this.id = name;
  85626. scene.lensFlareSystems.push(this);
  85627. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  85628. var engine = scene.getEngine();
  85629. // VBO
  85630. var vertices = [];
  85631. vertices.push(1, 1);
  85632. vertices.push(-1, 1);
  85633. vertices.push(-1, -1);
  85634. vertices.push(1, -1);
  85635. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85636. // Indices
  85637. var indices = [];
  85638. indices.push(0);
  85639. indices.push(1);
  85640. indices.push(2);
  85641. indices.push(0);
  85642. indices.push(2);
  85643. indices.push(3);
  85644. this._indexBuffer = engine.createIndexBuffer(indices);
  85645. // Effects
  85646. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  85647. }
  85648. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  85649. get: function () {
  85650. return this._isEnabled;
  85651. },
  85652. set: function (value) {
  85653. this._isEnabled = value;
  85654. },
  85655. enumerable: true,
  85656. configurable: true
  85657. });
  85658. LensFlareSystem.prototype.getScene = function () {
  85659. return this._scene;
  85660. };
  85661. LensFlareSystem.prototype.getEmitter = function () {
  85662. return this._emitter;
  85663. };
  85664. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  85665. this._emitter = newEmitter;
  85666. };
  85667. LensFlareSystem.prototype.getEmitterPosition = function () {
  85668. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  85669. };
  85670. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  85671. var position = this.getEmitterPosition();
  85672. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  85673. this._positionX = position.x;
  85674. this._positionY = position.y;
  85675. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  85676. if (this.viewportBorder > 0) {
  85677. globalViewport.x -= this.viewportBorder;
  85678. globalViewport.y -= this.viewportBorder;
  85679. globalViewport.width += this.viewportBorder * 2;
  85680. globalViewport.height += this.viewportBorder * 2;
  85681. position.x += this.viewportBorder;
  85682. position.y += this.viewportBorder;
  85683. this._positionX += this.viewportBorder;
  85684. this._positionY += this.viewportBorder;
  85685. }
  85686. if (position.z > 0) {
  85687. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  85688. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  85689. return true;
  85690. }
  85691. return true;
  85692. }
  85693. return false;
  85694. };
  85695. /** @hidden */
  85696. LensFlareSystem.prototype._isVisible = function () {
  85697. if (!this._isEnabled || !this._scene.activeCamera) {
  85698. return false;
  85699. }
  85700. var emitterPosition = this.getEmitterPosition();
  85701. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  85702. var distance = direction.length();
  85703. direction.normalize();
  85704. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  85705. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  85706. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  85707. };
  85708. LensFlareSystem.prototype.render = function () {
  85709. if (!this._effect.isReady() || !this._scene.activeCamera)
  85710. return false;
  85711. var engine = this._scene.getEngine();
  85712. var viewport = this._scene.activeCamera.viewport;
  85713. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  85714. // Position
  85715. if (!this.computeEffectivePosition(globalViewport)) {
  85716. return false;
  85717. }
  85718. // Visibility
  85719. if (!this._isVisible()) {
  85720. return false;
  85721. }
  85722. // Intensity
  85723. var awayX;
  85724. var awayY;
  85725. if (this._positionX < this.borderLimit + globalViewport.x) {
  85726. awayX = this.borderLimit + globalViewport.x - this._positionX;
  85727. }
  85728. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  85729. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  85730. }
  85731. else {
  85732. awayX = 0;
  85733. }
  85734. if (this._positionY < this.borderLimit + globalViewport.y) {
  85735. awayY = this.borderLimit + globalViewport.y - this._positionY;
  85736. }
  85737. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  85738. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  85739. }
  85740. else {
  85741. awayY = 0;
  85742. }
  85743. var away = (awayX > awayY) ? awayX : awayY;
  85744. away -= this.viewportBorder;
  85745. if (away > this.borderLimit) {
  85746. away = this.borderLimit;
  85747. }
  85748. var intensity = 1.0 - (away / this.borderLimit);
  85749. if (intensity < 0) {
  85750. return false;
  85751. }
  85752. if (intensity > 1.0) {
  85753. intensity = 1.0;
  85754. }
  85755. if (this.viewportBorder > 0) {
  85756. globalViewport.x += this.viewportBorder;
  85757. globalViewport.y += this.viewportBorder;
  85758. globalViewport.width -= this.viewportBorder * 2;
  85759. globalViewport.height -= this.viewportBorder * 2;
  85760. this._positionX -= this.viewportBorder;
  85761. this._positionY -= this.viewportBorder;
  85762. }
  85763. // Position
  85764. var centerX = globalViewport.x + globalViewport.width / 2;
  85765. var centerY = globalViewport.y + globalViewport.height / 2;
  85766. var distX = centerX - this._positionX;
  85767. var distY = centerY - this._positionY;
  85768. // Effects
  85769. engine.enableEffect(this._effect);
  85770. engine.setState(false);
  85771. engine.setDepthBuffer(false);
  85772. // VBOs
  85773. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  85774. // Flares
  85775. for (var index = 0; index < this.lensFlares.length; index++) {
  85776. var flare = this.lensFlares[index];
  85777. engine.setAlphaMode(flare.alphaMode);
  85778. var x = centerX - (distX * flare.position);
  85779. var y = centerY - (distY * flare.position);
  85780. var cw = flare.size;
  85781. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  85782. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  85783. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  85784. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  85785. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  85786. // Texture
  85787. this._effect.setTexture("textureSampler", flare.texture);
  85788. // Color
  85789. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  85790. // Draw order
  85791. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85792. }
  85793. engine.setDepthBuffer(true);
  85794. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85795. return true;
  85796. };
  85797. LensFlareSystem.prototype.dispose = function () {
  85798. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85799. if (vertexBuffer) {
  85800. vertexBuffer.dispose();
  85801. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85802. }
  85803. if (this._indexBuffer) {
  85804. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85805. this._indexBuffer = null;
  85806. }
  85807. while (this.lensFlares.length) {
  85808. this.lensFlares[0].dispose();
  85809. }
  85810. // Remove from scene
  85811. var index = this._scene.lensFlareSystems.indexOf(this);
  85812. this._scene.lensFlareSystems.splice(index, 1);
  85813. };
  85814. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  85815. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  85816. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  85817. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  85818. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  85819. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  85820. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  85821. var parsedFlare = parsedLensFlareSystem.flares[index];
  85822. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  85823. }
  85824. return lensFlareSystem;
  85825. };
  85826. LensFlareSystem.prototype.serialize = function () {
  85827. var serializationObject = {};
  85828. serializationObject.id = this.id;
  85829. serializationObject.name = this.name;
  85830. serializationObject.emitterId = this.getEmitter().id;
  85831. serializationObject.borderLimit = this.borderLimit;
  85832. serializationObject.flares = [];
  85833. for (var index = 0; index < this.lensFlares.length; index++) {
  85834. var flare = this.lensFlares[index];
  85835. serializationObject.flares.push({
  85836. size: flare.size,
  85837. position: flare.position,
  85838. color: flare.color.asArray(),
  85839. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  85840. });
  85841. }
  85842. return serializationObject;
  85843. };
  85844. return LensFlareSystem;
  85845. }());
  85846. BABYLON.LensFlareSystem = LensFlareSystem;
  85847. })(BABYLON || (BABYLON = {}));
  85848. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  85849. var BABYLON;
  85850. (function (BABYLON) {
  85851. /**
  85852. * This is a holder class for the physics joint created by the physics plugin.
  85853. * It holds a set of functions to control the underlying joint.
  85854. */
  85855. var PhysicsJoint = /** @class */ (function () {
  85856. function PhysicsJoint(type, jointData) {
  85857. this.type = type;
  85858. this.jointData = jointData;
  85859. jointData.nativeParams = jointData.nativeParams || {};
  85860. }
  85861. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  85862. get: function () {
  85863. return this._physicsJoint;
  85864. },
  85865. set: function (newJoint) {
  85866. if (this._physicsJoint) {
  85867. //remove from the wolrd
  85868. }
  85869. this._physicsJoint = newJoint;
  85870. },
  85871. enumerable: true,
  85872. configurable: true
  85873. });
  85874. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  85875. set: function (physicsPlugin) {
  85876. this._physicsPlugin = physicsPlugin;
  85877. },
  85878. enumerable: true,
  85879. configurable: true
  85880. });
  85881. /**
  85882. * Execute a function that is physics-plugin specific.
  85883. * @param {Function} func the function that will be executed.
  85884. * It accepts two parameters: the physics world and the physics joint.
  85885. */
  85886. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  85887. func(this._physicsPlugin.world, this._physicsJoint);
  85888. };
  85889. //TODO check if the native joints are the same
  85890. //Joint Types
  85891. PhysicsJoint.DistanceJoint = 0;
  85892. PhysicsJoint.HingeJoint = 1;
  85893. PhysicsJoint.BallAndSocketJoint = 2;
  85894. PhysicsJoint.WheelJoint = 3;
  85895. PhysicsJoint.SliderJoint = 4;
  85896. //OIMO
  85897. PhysicsJoint.PrismaticJoint = 5;
  85898. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  85899. PhysicsJoint.UniversalJoint = 6;
  85900. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  85901. //Cannon
  85902. //Similar to a Ball-Joint. Different in params
  85903. PhysicsJoint.PointToPointJoint = 8;
  85904. //Cannon only at the moment
  85905. PhysicsJoint.SpringJoint = 9;
  85906. PhysicsJoint.LockJoint = 10;
  85907. return PhysicsJoint;
  85908. }());
  85909. BABYLON.PhysicsJoint = PhysicsJoint;
  85910. /**
  85911. * A class representing a physics distance joint.
  85912. */
  85913. var DistanceJoint = /** @class */ (function (_super) {
  85914. __extends(DistanceJoint, _super);
  85915. function DistanceJoint(jointData) {
  85916. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  85917. }
  85918. /**
  85919. * Update the predefined distance.
  85920. */
  85921. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  85922. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  85923. };
  85924. return DistanceJoint;
  85925. }(PhysicsJoint));
  85926. BABYLON.DistanceJoint = DistanceJoint;
  85927. var MotorEnabledJoint = /** @class */ (function (_super) {
  85928. __extends(MotorEnabledJoint, _super);
  85929. function MotorEnabledJoint(type, jointData) {
  85930. return _super.call(this, type, jointData) || this;
  85931. }
  85932. /**
  85933. * Set the motor values.
  85934. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85935. * @param {number} force the force to apply
  85936. * @param {number} maxForce max force for this motor.
  85937. */
  85938. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  85939. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85940. };
  85941. /**
  85942. * Set the motor's limits.
  85943. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85944. */
  85945. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85946. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85947. };
  85948. return MotorEnabledJoint;
  85949. }(PhysicsJoint));
  85950. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  85951. /**
  85952. * This class represents a single hinge physics joint
  85953. */
  85954. var HingeJoint = /** @class */ (function (_super) {
  85955. __extends(HingeJoint, _super);
  85956. function HingeJoint(jointData) {
  85957. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  85958. }
  85959. /**
  85960. * Set the motor values.
  85961. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85962. * @param {number} force the force to apply
  85963. * @param {number} maxForce max force for this motor.
  85964. */
  85965. HingeJoint.prototype.setMotor = function (force, maxForce) {
  85966. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  85967. };
  85968. /**
  85969. * Set the motor's limits.
  85970. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85971. */
  85972. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  85973. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  85974. };
  85975. return HingeJoint;
  85976. }(MotorEnabledJoint));
  85977. BABYLON.HingeJoint = HingeJoint;
  85978. /**
  85979. * This class represents a dual hinge physics joint (same as wheel joint)
  85980. */
  85981. var Hinge2Joint = /** @class */ (function (_super) {
  85982. __extends(Hinge2Joint, _super);
  85983. function Hinge2Joint(jointData) {
  85984. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  85985. }
  85986. /**
  85987. * Set the motor values.
  85988. * Attention, this function is plugin specific. Engines won't react 100% the same.
  85989. * @param {number} force the force to apply
  85990. * @param {number} maxForce max force for this motor.
  85991. * @param {motorIndex} the motor's index, 0 or 1.
  85992. */
  85993. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  85994. if (motorIndex === void 0) { motorIndex = 0; }
  85995. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  85996. };
  85997. /**
  85998. * Set the motor limits.
  85999. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86000. * @param {number} upperLimit the upper limit
  86001. * @param {number} lowerLimit lower limit
  86002. * @param {motorIndex} the motor's index, 0 or 1.
  86003. */
  86004. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  86005. if (motorIndex === void 0) { motorIndex = 0; }
  86006. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  86007. };
  86008. return Hinge2Joint;
  86009. }(MotorEnabledJoint));
  86010. BABYLON.Hinge2Joint = Hinge2Joint;
  86011. })(BABYLON || (BABYLON = {}));
  86012. //# sourceMappingURL=babylon.physicsJoint.js.map
  86013. var BABYLON;
  86014. (function (BABYLON) {
  86015. var PhysicsImpostor = /** @class */ (function () {
  86016. function PhysicsImpostor(object, type, _options, _scene) {
  86017. if (_options === void 0) { _options = { mass: 0 }; }
  86018. var _this = this;
  86019. this.object = object;
  86020. this.type = type;
  86021. this._options = _options;
  86022. this._scene = _scene;
  86023. this._bodyUpdateRequired = false;
  86024. this._onBeforePhysicsStepCallbacks = new Array();
  86025. this._onAfterPhysicsStepCallbacks = new Array();
  86026. this._onPhysicsCollideCallbacks = [];
  86027. this._deltaPosition = BABYLON.Vector3.Zero();
  86028. this._isDisposed = false;
  86029. //temp variables for parent rotation calculations
  86030. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  86031. this._tmpQuat = new BABYLON.Quaternion();
  86032. this._tmpQuat2 = new BABYLON.Quaternion();
  86033. /**
  86034. * this function is executed by the physics engine.
  86035. */
  86036. this.beforeStep = function () {
  86037. if (!_this._physicsEngine) {
  86038. return;
  86039. }
  86040. _this.object.translate(_this._deltaPosition, -1);
  86041. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  86042. _this.object.computeWorldMatrix(false);
  86043. if (_this.object.parent && _this.object.rotationQuaternion) {
  86044. _this.getParentsRotation();
  86045. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  86046. }
  86047. else {
  86048. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  86049. }
  86050. if (!_this._options.disableBidirectionalTransformation) {
  86051. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  86052. }
  86053. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  86054. func(_this);
  86055. });
  86056. };
  86057. /**
  86058. * this function is executed by the physics engine.
  86059. */
  86060. this.afterStep = function () {
  86061. if (!_this._physicsEngine) {
  86062. return;
  86063. }
  86064. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  86065. func(_this);
  86066. });
  86067. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  86068. // object has now its world rotation. needs to be converted to local.
  86069. if (_this.object.parent && _this.object.rotationQuaternion) {
  86070. _this.getParentsRotation();
  86071. _this._tmpQuat.conjugateInPlace();
  86072. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  86073. }
  86074. // take the position set and make it the absolute position of this object.
  86075. _this.object.setAbsolutePosition(_this.object.position);
  86076. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  86077. _this.object.translate(_this._deltaPosition, 1);
  86078. };
  86079. /**
  86080. * Legacy collision detection event support
  86081. */
  86082. this.onCollideEvent = null;
  86083. //event and body object due to cannon's event-based architecture.
  86084. this.onCollide = function (e) {
  86085. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  86086. return;
  86087. }
  86088. if (!_this._physicsEngine) {
  86089. return;
  86090. }
  86091. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  86092. if (otherImpostor) {
  86093. // Legacy collision detection event support
  86094. if (_this.onCollideEvent) {
  86095. _this.onCollideEvent(_this, otherImpostor);
  86096. }
  86097. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  86098. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  86099. }).forEach(function (obj) {
  86100. obj.callback(_this, otherImpostor);
  86101. });
  86102. }
  86103. };
  86104. //sanity check!
  86105. if (!this.object) {
  86106. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  86107. return;
  86108. }
  86109. //legacy support for old syntax.
  86110. if (!this._scene && object.getScene) {
  86111. this._scene = object.getScene();
  86112. }
  86113. if (!this._scene) {
  86114. return;
  86115. }
  86116. this._physicsEngine = this._scene.getPhysicsEngine();
  86117. if (!this._physicsEngine) {
  86118. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  86119. }
  86120. else {
  86121. //set the object's quaternion, if not set
  86122. if (!this.object.rotationQuaternion) {
  86123. if (this.object.rotation) {
  86124. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  86125. }
  86126. else {
  86127. this.object.rotationQuaternion = new BABYLON.Quaternion();
  86128. }
  86129. }
  86130. //default options params
  86131. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  86132. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  86133. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  86134. this._joints = [];
  86135. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  86136. if (!this.object.parent || this._options.ignoreParent) {
  86137. this._init();
  86138. }
  86139. else if (this.object.parent.physicsImpostor) {
  86140. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  86141. }
  86142. }
  86143. }
  86144. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  86145. get: function () {
  86146. return this._isDisposed;
  86147. },
  86148. enumerable: true,
  86149. configurable: true
  86150. });
  86151. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  86152. get: function () {
  86153. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  86154. },
  86155. set: function (value) {
  86156. this.setMass(value);
  86157. },
  86158. enumerable: true,
  86159. configurable: true
  86160. });
  86161. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  86162. get: function () {
  86163. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  86164. },
  86165. set: function (value) {
  86166. if (!this._physicsEngine) {
  86167. return;
  86168. }
  86169. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  86170. },
  86171. enumerable: true,
  86172. configurable: true
  86173. });
  86174. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  86175. get: function () {
  86176. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  86177. },
  86178. set: function (value) {
  86179. if (!this._physicsEngine) {
  86180. return;
  86181. }
  86182. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  86183. },
  86184. enumerable: true,
  86185. configurable: true
  86186. });
  86187. /**
  86188. * This function will completly initialize this impostor.
  86189. * It will create a new body - but only if this mesh has no parent.
  86190. * If it has, this impostor will not be used other than to define the impostor
  86191. * of the child mesh.
  86192. * @hidden
  86193. */
  86194. PhysicsImpostor.prototype._init = function () {
  86195. if (!this._physicsEngine) {
  86196. return;
  86197. }
  86198. this._physicsEngine.removeImpostor(this);
  86199. this.physicsBody = null;
  86200. this._parent = this._parent || this._getPhysicsParent();
  86201. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  86202. this._physicsEngine.addImpostor(this);
  86203. }
  86204. };
  86205. PhysicsImpostor.prototype._getPhysicsParent = function () {
  86206. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  86207. var parentMesh = this.object.parent;
  86208. return parentMesh.physicsImpostor;
  86209. }
  86210. return null;
  86211. };
  86212. /**
  86213. * Should a new body be generated.
  86214. */
  86215. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  86216. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  86217. };
  86218. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  86219. this.forceUpdate();
  86220. };
  86221. /**
  86222. * Force a regeneration of this or the parent's impostor's body.
  86223. * Use under cautious - This will remove all joints already implemented.
  86224. */
  86225. PhysicsImpostor.prototype.forceUpdate = function () {
  86226. this._init();
  86227. if (this.parent && !this._options.ignoreParent) {
  86228. this.parent.forceUpdate();
  86229. }
  86230. };
  86231. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  86232. /*public get mesh(): AbstractMesh {
  86233. return this._mesh;
  86234. }*/
  86235. /**
  86236. * Gets the body that holds this impostor. Either its own, or its parent.
  86237. */
  86238. get: function () {
  86239. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  86240. },
  86241. /**
  86242. * Set the physics body. Used mainly by the physics engine/plugin
  86243. */
  86244. set: function (physicsBody) {
  86245. if (this._physicsBody && this._physicsEngine) {
  86246. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  86247. }
  86248. this._physicsBody = physicsBody;
  86249. this.resetUpdateFlags();
  86250. },
  86251. enumerable: true,
  86252. configurable: true
  86253. });
  86254. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  86255. get: function () {
  86256. return !this._options.ignoreParent && this._parent ? this._parent : null;
  86257. },
  86258. set: function (value) {
  86259. this._parent = value;
  86260. },
  86261. enumerable: true,
  86262. configurable: true
  86263. });
  86264. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  86265. this._bodyUpdateRequired = false;
  86266. };
  86267. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  86268. if (this.object.getBoundingInfo) {
  86269. var q = this.object.rotationQuaternion;
  86270. //reset rotation
  86271. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  86272. //calculate the world matrix with no rotation
  86273. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  86274. var boundingInfo = this.object.getBoundingInfo();
  86275. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  86276. //bring back the rotation
  86277. this.object.rotationQuaternion = q;
  86278. //calculate the world matrix with the new rotation
  86279. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  86280. return size;
  86281. }
  86282. else {
  86283. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  86284. }
  86285. };
  86286. PhysicsImpostor.prototype.getObjectCenter = function () {
  86287. if (this.object.getBoundingInfo) {
  86288. var boundingInfo = this.object.getBoundingInfo();
  86289. return boundingInfo.boundingBox.centerWorld;
  86290. }
  86291. else {
  86292. return this.object.position;
  86293. }
  86294. };
  86295. /**
  86296. * Get a specific parametes from the options parameter.
  86297. */
  86298. PhysicsImpostor.prototype.getParam = function (paramName) {
  86299. return this._options[paramName];
  86300. };
  86301. /**
  86302. * Sets a specific parameter in the options given to the physics plugin
  86303. */
  86304. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  86305. this._options[paramName] = value;
  86306. this._bodyUpdateRequired = true;
  86307. };
  86308. /**
  86309. * Specifically change the body's mass option. Won't recreate the physics body object
  86310. */
  86311. PhysicsImpostor.prototype.setMass = function (mass) {
  86312. if (this.getParam("mass") !== mass) {
  86313. this.setParam("mass", mass);
  86314. }
  86315. if (this._physicsEngine) {
  86316. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  86317. }
  86318. };
  86319. PhysicsImpostor.prototype.getLinearVelocity = function () {
  86320. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  86321. };
  86322. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  86323. if (this._physicsEngine) {
  86324. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  86325. }
  86326. };
  86327. PhysicsImpostor.prototype.getAngularVelocity = function () {
  86328. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  86329. };
  86330. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  86331. if (this._physicsEngine) {
  86332. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  86333. }
  86334. };
  86335. /**
  86336. * Execute a function with the physics plugin native code.
  86337. * Provide a function the will have two variables - the world object and the physics body object.
  86338. */
  86339. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  86340. if (this._physicsEngine) {
  86341. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  86342. }
  86343. };
  86344. /**
  86345. * Register a function that will be executed before the physics world is stepping forward.
  86346. */
  86347. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  86348. this._onBeforePhysicsStepCallbacks.push(func);
  86349. };
  86350. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  86351. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  86352. if (index > -1) {
  86353. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  86354. }
  86355. else {
  86356. BABYLON.Tools.Warn("Function to remove was not found");
  86357. }
  86358. };
  86359. /**
  86360. * Register a function that will be executed after the physics step
  86361. */
  86362. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  86363. this._onAfterPhysicsStepCallbacks.push(func);
  86364. };
  86365. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  86366. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  86367. if (index > -1) {
  86368. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  86369. }
  86370. else {
  86371. BABYLON.Tools.Warn("Function to remove was not found");
  86372. }
  86373. };
  86374. /**
  86375. * register a function that will be executed when this impostor collides against a different body.
  86376. */
  86377. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  86378. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  86379. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  86380. };
  86381. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  86382. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  86383. var index = -1;
  86384. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  86385. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  86386. // chcek the arrays match
  86387. var sameList = cbDef.otherImpostors.every(function (impostor) {
  86388. return collidedAgainstList.indexOf(impostor) > -1;
  86389. });
  86390. if (sameList) {
  86391. index = idx;
  86392. }
  86393. return sameList;
  86394. }
  86395. return false;
  86396. });
  86397. if (found) {
  86398. this._onPhysicsCollideCallbacks.splice(index, 1);
  86399. }
  86400. else {
  86401. BABYLON.Tools.Warn("Function to remove was not found");
  86402. }
  86403. };
  86404. PhysicsImpostor.prototype.getParentsRotation = function () {
  86405. var parent = this.object.parent;
  86406. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  86407. while (parent) {
  86408. if (parent.rotationQuaternion) {
  86409. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  86410. }
  86411. else {
  86412. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  86413. }
  86414. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  86415. parent = parent.parent;
  86416. }
  86417. return this._tmpQuat;
  86418. };
  86419. /**
  86420. * Apply a force
  86421. */
  86422. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  86423. if (this._physicsEngine) {
  86424. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  86425. }
  86426. return this;
  86427. };
  86428. /**
  86429. * Apply an impulse
  86430. */
  86431. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  86432. if (this._physicsEngine) {
  86433. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  86434. }
  86435. return this;
  86436. };
  86437. /**
  86438. * A help function to create a joint.
  86439. */
  86440. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  86441. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  86442. this.addJoint(otherImpostor, joint);
  86443. return this;
  86444. };
  86445. /**
  86446. * Add a joint to this impostor with a different impostor.
  86447. */
  86448. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  86449. this._joints.push({
  86450. otherImpostor: otherImpostor,
  86451. joint: joint
  86452. });
  86453. if (this._physicsEngine) {
  86454. this._physicsEngine.addJoint(this, otherImpostor, joint);
  86455. }
  86456. return this;
  86457. };
  86458. /**
  86459. * Will keep this body still, in a sleep mode.
  86460. */
  86461. PhysicsImpostor.prototype.sleep = function () {
  86462. if (this._physicsEngine) {
  86463. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  86464. }
  86465. return this;
  86466. };
  86467. /**
  86468. * Wake the body up.
  86469. */
  86470. PhysicsImpostor.prototype.wakeUp = function () {
  86471. if (this._physicsEngine) {
  86472. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  86473. }
  86474. return this;
  86475. };
  86476. PhysicsImpostor.prototype.clone = function (newObject) {
  86477. if (!newObject)
  86478. return null;
  86479. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  86480. };
  86481. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  86482. var _this = this;
  86483. //no dispose if no physics engine is available.
  86484. if (!this._physicsEngine) {
  86485. return;
  86486. }
  86487. this._joints.forEach(function (j) {
  86488. if (_this._physicsEngine) {
  86489. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  86490. }
  86491. });
  86492. //dispose the physics body
  86493. this._physicsEngine.removeImpostor(this);
  86494. if (this.parent) {
  86495. this.parent.forceUpdate();
  86496. }
  86497. else {
  86498. /*this._object.getChildMeshes().forEach(function(mesh) {
  86499. if (mesh.physicsImpostor) {
  86500. if (disposeChildren) {
  86501. mesh.physicsImpostor.dispose();
  86502. mesh.physicsImpostor = null;
  86503. }
  86504. }
  86505. })*/
  86506. }
  86507. this._isDisposed = true;
  86508. };
  86509. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  86510. this._deltaPosition.copyFrom(position);
  86511. };
  86512. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  86513. if (!this._deltaRotation) {
  86514. this._deltaRotation = new BABYLON.Quaternion();
  86515. }
  86516. this._deltaRotation.copyFrom(rotation);
  86517. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  86518. };
  86519. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  86520. if (this._physicsEngine) {
  86521. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  86522. }
  86523. return this;
  86524. };
  86525. PhysicsImpostor.prototype.getRadius = function () {
  86526. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  86527. };
  86528. /**
  86529. * Sync a bone with this impostor
  86530. * @param bone The bone to sync to the impostor.
  86531. * @param boneMesh The mesh that the bone is influencing.
  86532. * @param jointPivot The pivot of the joint / bone in local space.
  86533. * @param distToJoint Optional distance from the impostor to the joint.
  86534. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  86535. */
  86536. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  86537. var tempVec = PhysicsImpostor._tmpVecs[0];
  86538. var mesh = this.object;
  86539. if (mesh.rotationQuaternion) {
  86540. if (adjustRotation) {
  86541. var tempQuat = PhysicsImpostor._tmpQuat;
  86542. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  86543. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  86544. }
  86545. else {
  86546. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  86547. }
  86548. }
  86549. tempVec.x = 0;
  86550. tempVec.y = 0;
  86551. tempVec.z = 0;
  86552. if (jointPivot) {
  86553. tempVec.x = jointPivot.x;
  86554. tempVec.y = jointPivot.y;
  86555. tempVec.z = jointPivot.z;
  86556. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  86557. if (distToJoint === undefined || distToJoint === null) {
  86558. distToJoint = jointPivot.length();
  86559. }
  86560. tempVec.x *= distToJoint;
  86561. tempVec.y *= distToJoint;
  86562. tempVec.z *= distToJoint;
  86563. }
  86564. if (bone.getParent()) {
  86565. tempVec.addInPlace(mesh.getAbsolutePosition());
  86566. bone.setAbsolutePosition(tempVec, boneMesh);
  86567. }
  86568. else {
  86569. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  86570. boneMesh.position.x -= tempVec.x;
  86571. boneMesh.position.y -= tempVec.y;
  86572. boneMesh.position.z -= tempVec.z;
  86573. }
  86574. };
  86575. /**
  86576. * Sync impostor to a bone
  86577. * @param bone The bone that the impostor will be synced to.
  86578. * @param boneMesh The mesh that the bone is influencing.
  86579. * @param jointPivot The pivot of the joint / bone in local space.
  86580. * @param distToJoint Optional distance from the impostor to the joint.
  86581. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  86582. * @param boneAxis Optional vector3 axis the bone is aligned with
  86583. */
  86584. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  86585. var mesh = this.object;
  86586. if (mesh.rotationQuaternion) {
  86587. if (adjustRotation) {
  86588. var tempQuat = PhysicsImpostor._tmpQuat;
  86589. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  86590. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  86591. }
  86592. else {
  86593. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  86594. }
  86595. }
  86596. var pos = PhysicsImpostor._tmpVecs[0];
  86597. var boneDir = PhysicsImpostor._tmpVecs[1];
  86598. if (!boneAxis) {
  86599. boneAxis = PhysicsImpostor._tmpVecs[2];
  86600. boneAxis.x = 0;
  86601. boneAxis.y = 1;
  86602. boneAxis.z = 0;
  86603. }
  86604. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  86605. bone.getAbsolutePositionToRef(boneMesh, pos);
  86606. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  86607. distToJoint = jointPivot.length();
  86608. }
  86609. if (distToJoint !== undefined && distToJoint !== null) {
  86610. pos.x += boneDir.x * distToJoint;
  86611. pos.y += boneDir.y * distToJoint;
  86612. pos.z += boneDir.z * distToJoint;
  86613. }
  86614. mesh.setAbsolutePosition(pos);
  86615. };
  86616. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  86617. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  86618. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86619. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  86620. //Impostor types
  86621. PhysicsImpostor.NoImpostor = 0;
  86622. PhysicsImpostor.SphereImpostor = 1;
  86623. PhysicsImpostor.BoxImpostor = 2;
  86624. PhysicsImpostor.PlaneImpostor = 3;
  86625. PhysicsImpostor.MeshImpostor = 4;
  86626. PhysicsImpostor.CylinderImpostor = 7;
  86627. PhysicsImpostor.ParticleImpostor = 8;
  86628. PhysicsImpostor.HeightmapImpostor = 9;
  86629. return PhysicsImpostor;
  86630. }());
  86631. BABYLON.PhysicsImpostor = PhysicsImpostor;
  86632. })(BABYLON || (BABYLON = {}));
  86633. //# sourceMappingURL=babylon.physicsImpostor.js.map
  86634. var BABYLON;
  86635. (function (BABYLON) {
  86636. var PhysicsEngine = /** @class */ (function () {
  86637. function PhysicsEngine(gravity, _physicsPlugin) {
  86638. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  86639. this._physicsPlugin = _physicsPlugin;
  86640. //new methods and parameters
  86641. this._impostors = [];
  86642. this._joints = [];
  86643. if (!this._physicsPlugin.isSupported()) {
  86644. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  86645. + "Please make sure it is included.");
  86646. }
  86647. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  86648. this.setGravity(gravity);
  86649. this.setTimeStep();
  86650. }
  86651. PhysicsEngine.prototype.setGravity = function (gravity) {
  86652. this.gravity = gravity;
  86653. this._physicsPlugin.setGravity(this.gravity);
  86654. };
  86655. /**
  86656. * Set the time step of the physics engine.
  86657. * default is 1/60.
  86658. * To slow it down, enter 1/600 for example.
  86659. * To speed it up, 1/30
  86660. * @param {number} newTimeStep the new timestep to apply to this world.
  86661. */
  86662. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  86663. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  86664. this._physicsPlugin.setTimeStep(newTimeStep);
  86665. };
  86666. /**
  86667. * Get the time step of the physics engine.
  86668. */
  86669. PhysicsEngine.prototype.getTimeStep = function () {
  86670. return this._physicsPlugin.getTimeStep();
  86671. };
  86672. PhysicsEngine.prototype.dispose = function () {
  86673. this._impostors.forEach(function (impostor) {
  86674. impostor.dispose();
  86675. });
  86676. this._physicsPlugin.dispose();
  86677. };
  86678. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  86679. return this._physicsPlugin.name;
  86680. };
  86681. /**
  86682. * Adding a new impostor for the impostor tracking.
  86683. * This will be done by the impostor itself.
  86684. * @param {PhysicsImpostor} impostor the impostor to add
  86685. */
  86686. PhysicsEngine.prototype.addImpostor = function (impostor) {
  86687. impostor.uniqueId = this._impostors.push(impostor);
  86688. //if no parent, generate the body
  86689. if (!impostor.parent) {
  86690. this._physicsPlugin.generatePhysicsBody(impostor);
  86691. }
  86692. };
  86693. /**
  86694. * Remove an impostor from the engine.
  86695. * This impostor and its mesh will not longer be updated by the physics engine.
  86696. * @param {PhysicsImpostor} impostor the impostor to remove
  86697. */
  86698. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  86699. var index = this._impostors.indexOf(impostor);
  86700. if (index > -1) {
  86701. var removed = this._impostors.splice(index, 1);
  86702. //Is it needed?
  86703. if (removed.length) {
  86704. //this will also remove it from the world.
  86705. removed[0].physicsBody = null;
  86706. }
  86707. }
  86708. };
  86709. /**
  86710. * Add a joint to the physics engine
  86711. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  86712. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  86713. * @param {PhysicsJoint} the joint that will connect both impostors.
  86714. */
  86715. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  86716. var impostorJoint = {
  86717. mainImpostor: mainImpostor,
  86718. connectedImpostor: connectedImpostor,
  86719. joint: joint
  86720. };
  86721. joint.physicsPlugin = this._physicsPlugin;
  86722. this._joints.push(impostorJoint);
  86723. this._physicsPlugin.generateJoint(impostorJoint);
  86724. };
  86725. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  86726. var matchingJoints = this._joints.filter(function (impostorJoint) {
  86727. return (impostorJoint.connectedImpostor === connectedImpostor
  86728. && impostorJoint.joint === joint
  86729. && impostorJoint.mainImpostor === mainImpostor);
  86730. });
  86731. if (matchingJoints.length) {
  86732. this._physicsPlugin.removeJoint(matchingJoints[0]);
  86733. //TODO remove it from the list as well
  86734. }
  86735. };
  86736. /**
  86737. * Called by the scene. no need to call it.
  86738. * @hidden
  86739. */
  86740. PhysicsEngine.prototype._step = function (delta) {
  86741. var _this = this;
  86742. //check if any mesh has no body / requires an update
  86743. this._impostors.forEach(function (impostor) {
  86744. if (impostor.isBodyInitRequired()) {
  86745. _this._physicsPlugin.generatePhysicsBody(impostor);
  86746. }
  86747. });
  86748. if (delta > 0.1) {
  86749. delta = 0.1;
  86750. }
  86751. else if (delta <= 0) {
  86752. delta = 1.0 / 60.0;
  86753. }
  86754. this._physicsPlugin.executeStep(delta, this._impostors);
  86755. };
  86756. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  86757. return this._physicsPlugin;
  86758. };
  86759. PhysicsEngine.prototype.getImpostors = function () {
  86760. return this._impostors;
  86761. };
  86762. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  86763. for (var i = 0; i < this._impostors.length; ++i) {
  86764. if (this._impostors[i].object === object) {
  86765. return this._impostors[i];
  86766. }
  86767. }
  86768. return null;
  86769. };
  86770. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  86771. for (var i = 0; i < this._impostors.length; ++i) {
  86772. if (this._impostors[i].physicsBody === body) {
  86773. return this._impostors[i];
  86774. }
  86775. }
  86776. return null;
  86777. };
  86778. // Statics
  86779. PhysicsEngine.Epsilon = 0.001;
  86780. return PhysicsEngine;
  86781. }());
  86782. BABYLON.PhysicsEngine = PhysicsEngine;
  86783. })(BABYLON || (BABYLON = {}));
  86784. //# sourceMappingURL=babylon.physicsEngine.js.map
  86785. var BABYLON;
  86786. (function (BABYLON) {
  86787. var PhysicsHelper = /** @class */ (function () {
  86788. function PhysicsHelper(scene) {
  86789. this._scene = scene;
  86790. this._physicsEngine = this._scene.getPhysicsEngine();
  86791. if (!this._physicsEngine) {
  86792. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  86793. }
  86794. }
  86795. /**
  86796. * @param {Vector3} origin the origin of the explosion
  86797. * @param {number} radius the explosion radius
  86798. * @param {number} strength the explosion strength
  86799. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86800. */
  86801. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  86802. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86803. if (!this._physicsEngine) {
  86804. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  86805. return null;
  86806. }
  86807. var impostors = this._physicsEngine.getImpostors();
  86808. if (impostors.length === 0) {
  86809. return null;
  86810. }
  86811. var event = new PhysicsRadialExplosionEvent(this._scene);
  86812. impostors.forEach(function (impostor) {
  86813. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86814. if (!impostorForceAndContactPoint) {
  86815. return;
  86816. }
  86817. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86818. });
  86819. event.dispose(false);
  86820. return event;
  86821. };
  86822. /**
  86823. * @param {Vector3} origin the origin of the explosion
  86824. * @param {number} radius the explosion radius
  86825. * @param {number} strength the explosion strength
  86826. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86827. */
  86828. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  86829. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86830. if (!this._physicsEngine) {
  86831. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86832. return null;
  86833. }
  86834. var impostors = this._physicsEngine.getImpostors();
  86835. if (impostors.length === 0) {
  86836. return null;
  86837. }
  86838. var event = new PhysicsRadialExplosionEvent(this._scene);
  86839. impostors.forEach(function (impostor) {
  86840. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  86841. if (!impostorForceAndContactPoint) {
  86842. return;
  86843. }
  86844. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86845. });
  86846. event.dispose(false);
  86847. return event;
  86848. };
  86849. /**
  86850. * @param {Vector3} origin the origin of the explosion
  86851. * @param {number} radius the explosion radius
  86852. * @param {number} strength the explosion strength
  86853. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  86854. */
  86855. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  86856. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  86857. if (!this._physicsEngine) {
  86858. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86859. return null;
  86860. }
  86861. var impostors = this._physicsEngine.getImpostors();
  86862. if (impostors.length === 0) {
  86863. return null;
  86864. }
  86865. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  86866. event.dispose(false);
  86867. return event;
  86868. };
  86869. /**
  86870. * @param {Vector3} origin the origin of the updraft
  86871. * @param {number} radius the radius of the updraft
  86872. * @param {number} strength the strength of the updraft
  86873. * @param {number} height the height of the updraft
  86874. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  86875. */
  86876. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  86877. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  86878. if (!this._physicsEngine) {
  86879. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86880. return null;
  86881. }
  86882. if (this._physicsEngine.getImpostors().length === 0) {
  86883. return null;
  86884. }
  86885. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  86886. event.dispose(false);
  86887. return event;
  86888. };
  86889. /**
  86890. * @param {Vector3} origin the of the vortex
  86891. * @param {number} radius the radius of the vortex
  86892. * @param {number} strength the strength of the vortex
  86893. * @param {number} height the height of the vortex
  86894. */
  86895. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  86896. if (!this._physicsEngine) {
  86897. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  86898. return null;
  86899. }
  86900. if (this._physicsEngine.getImpostors().length === 0) {
  86901. return null;
  86902. }
  86903. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  86904. event.dispose(false);
  86905. return event;
  86906. };
  86907. return PhysicsHelper;
  86908. }());
  86909. BABYLON.PhysicsHelper = PhysicsHelper;
  86910. /***** Radial explosion *****/
  86911. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  86912. function PhysicsRadialExplosionEvent(scene) {
  86913. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  86914. this._rays = [];
  86915. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  86916. this._scene = scene;
  86917. }
  86918. /**
  86919. * Returns the data related to the radial explosion event (sphere & rays).
  86920. * @returns {PhysicsRadialExplosionEventData}
  86921. */
  86922. PhysicsRadialExplosionEvent.prototype.getData = function () {
  86923. this._dataFetched = true;
  86924. return {
  86925. sphere: this._sphere,
  86926. rays: this._rays,
  86927. };
  86928. };
  86929. /**
  86930. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  86931. * @param impostor
  86932. * @param {Vector3} origin the origin of the explosion
  86933. * @param {number} radius the explosion radius
  86934. * @param {number} strength the explosion strength
  86935. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  86936. * @returns {Nullable<PhysicsForceAndContactPoint>}
  86937. */
  86938. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  86939. if (impostor.mass === 0) {
  86940. return null;
  86941. }
  86942. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  86943. return null;
  86944. }
  86945. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86946. return null;
  86947. }
  86948. var impostorObjectCenter = impostor.getObjectCenter();
  86949. var direction = impostorObjectCenter.subtract(origin);
  86950. var ray = new BABYLON.Ray(origin, direction, radius);
  86951. this._rays.push(ray);
  86952. var hit = ray.intersectsMesh(impostor.object);
  86953. var contactPoint = hit.pickedPoint;
  86954. if (!contactPoint) {
  86955. return null;
  86956. }
  86957. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  86958. if (distanceFromOrigin > radius) {
  86959. return null;
  86960. }
  86961. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  86962. ? strength
  86963. : strength * (1 - (distanceFromOrigin / radius));
  86964. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86965. return { force: force, contactPoint: contactPoint };
  86966. };
  86967. /**
  86968. * Disposes the sphere.
  86969. * @param {bolean} force
  86970. */
  86971. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  86972. var _this = this;
  86973. if (force === void 0) { force = true; }
  86974. if (force) {
  86975. this._sphere.dispose();
  86976. }
  86977. else {
  86978. setTimeout(function () {
  86979. if (!_this._dataFetched) {
  86980. _this._sphere.dispose();
  86981. }
  86982. }, 0);
  86983. }
  86984. };
  86985. /*** Helpers ***/
  86986. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  86987. if (!this._sphere) {
  86988. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  86989. this._sphere.isVisible = false;
  86990. }
  86991. };
  86992. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  86993. var impostorObject = impostor.object;
  86994. this._prepareSphere();
  86995. this._sphere.position = origin;
  86996. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  86997. this._sphere._updateBoundingInfo();
  86998. this._sphere.computeWorldMatrix(true);
  86999. return this._sphere.intersectsMesh(impostorObject, true);
  87000. };
  87001. return PhysicsRadialExplosionEvent;
  87002. }());
  87003. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  87004. /***** Gravitational Field *****/
  87005. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  87006. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  87007. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87008. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87009. this._physicsHelper = physicsHelper;
  87010. this._scene = scene;
  87011. this._origin = origin;
  87012. this._radius = radius;
  87013. this._strength = strength;
  87014. this._falloff = falloff;
  87015. this._tickCallback = this._tick.bind(this);
  87016. }
  87017. /**
  87018. * Returns the data related to the gravitational field event (sphere).
  87019. * @returns {PhysicsGravitationalFieldEventData}
  87020. */
  87021. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  87022. this._dataFetched = true;
  87023. return {
  87024. sphere: this._sphere,
  87025. };
  87026. };
  87027. /**
  87028. * Enables the gravitational field.
  87029. */
  87030. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  87031. this._tickCallback.call(this);
  87032. this._scene.registerBeforeRender(this._tickCallback);
  87033. };
  87034. /**
  87035. * Disables the gravitational field.
  87036. */
  87037. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  87038. this._scene.unregisterBeforeRender(this._tickCallback);
  87039. };
  87040. /**
  87041. * Disposes the sphere.
  87042. * @param {bolean} force
  87043. */
  87044. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  87045. var _this = this;
  87046. if (force === void 0) { force = true; }
  87047. if (force) {
  87048. this._sphere.dispose();
  87049. }
  87050. else {
  87051. setTimeout(function () {
  87052. if (!_this._dataFetched) {
  87053. _this._sphere.dispose();
  87054. }
  87055. }, 0);
  87056. }
  87057. };
  87058. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  87059. // Since the params won't change, we fetch the event only once
  87060. if (this._sphere) {
  87061. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87062. }
  87063. else {
  87064. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87065. if (radialExplosionEvent) {
  87066. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  87067. }
  87068. }
  87069. };
  87070. return PhysicsGravitationalFieldEvent;
  87071. }());
  87072. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  87073. /***** Updraft *****/
  87074. var PhysicsUpdraftEvent = /** @class */ (function () {
  87075. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  87076. this._scene = _scene;
  87077. this._origin = _origin;
  87078. this._radius = _radius;
  87079. this._strength = _strength;
  87080. this._height = _height;
  87081. this._updraftMode = _updraftMode;
  87082. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  87083. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  87084. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  87085. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87086. this._physicsEngine = this._scene.getPhysicsEngine();
  87087. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  87088. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  87089. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87090. this._originDirection = this._origin.subtract(this._originTop).normalize();
  87091. }
  87092. this._tickCallback = this._tick.bind(this);
  87093. }
  87094. /**
  87095. * Returns the data related to the updraft event (cylinder).
  87096. * @returns {PhysicsUpdraftEventData}
  87097. */
  87098. PhysicsUpdraftEvent.prototype.getData = function () {
  87099. this._dataFetched = true;
  87100. return {
  87101. cylinder: this._cylinder,
  87102. };
  87103. };
  87104. /**
  87105. * Enables the updraft.
  87106. */
  87107. PhysicsUpdraftEvent.prototype.enable = function () {
  87108. this._tickCallback.call(this);
  87109. this._scene.registerBeforeRender(this._tickCallback);
  87110. };
  87111. /**
  87112. * Disables the cortex.
  87113. */
  87114. PhysicsUpdraftEvent.prototype.disable = function () {
  87115. this._scene.unregisterBeforeRender(this._tickCallback);
  87116. };
  87117. /**
  87118. * Disposes the sphere.
  87119. * @param {bolean} force
  87120. */
  87121. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  87122. var _this = this;
  87123. if (force === void 0) { force = true; }
  87124. if (force) {
  87125. this._cylinder.dispose();
  87126. }
  87127. else {
  87128. setTimeout(function () {
  87129. if (!_this._dataFetched) {
  87130. _this._cylinder.dispose();
  87131. }
  87132. }, 0);
  87133. }
  87134. };
  87135. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  87136. if (impostor.mass === 0) {
  87137. return null;
  87138. }
  87139. if (!this._intersectsWithCylinder(impostor)) {
  87140. return null;
  87141. }
  87142. var impostorObjectCenter = impostor.getObjectCenter();
  87143. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87144. var direction = this._originDirection;
  87145. }
  87146. else {
  87147. var direction = impostorObjectCenter.subtract(this._originTop);
  87148. }
  87149. var multiplier = this._strength * -1;
  87150. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87151. return { force: force, contactPoint: impostorObjectCenter };
  87152. };
  87153. PhysicsUpdraftEvent.prototype._tick = function () {
  87154. var _this = this;
  87155. this._physicsEngine.getImpostors().forEach(function (impostor) {
  87156. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  87157. if (!impostorForceAndContactPoint) {
  87158. return;
  87159. }
  87160. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87161. });
  87162. };
  87163. /*** Helpers ***/
  87164. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  87165. if (!this._cylinder) {
  87166. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  87167. height: this._height,
  87168. diameter: this._radius * 2,
  87169. }, this._scene);
  87170. this._cylinder.isVisible = false;
  87171. }
  87172. };
  87173. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  87174. var impostorObject = impostor.object;
  87175. this._prepareCylinder();
  87176. this._cylinder.position = this._cylinderPosition;
  87177. return this._cylinder.intersectsMesh(impostorObject, true);
  87178. };
  87179. return PhysicsUpdraftEvent;
  87180. }());
  87181. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  87182. /***** Vortex *****/
  87183. var PhysicsVortexEvent = /** @class */ (function () {
  87184. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  87185. this._scene = _scene;
  87186. this._origin = _origin;
  87187. this._radius = _radius;
  87188. this._strength = _strength;
  87189. this._height = _height;
  87190. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  87191. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  87192. this._updraftMultiplier = 0.02;
  87193. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  87194. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87195. this._physicsEngine = this._scene.getPhysicsEngine();
  87196. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  87197. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  87198. this._tickCallback = this._tick.bind(this);
  87199. }
  87200. /**
  87201. * Returns the data related to the vortex event (cylinder).
  87202. * @returns {PhysicsVortexEventData}
  87203. */
  87204. PhysicsVortexEvent.prototype.getData = function () {
  87205. this._dataFetched = true;
  87206. return {
  87207. cylinder: this._cylinder,
  87208. };
  87209. };
  87210. /**
  87211. * Enables the vortex.
  87212. */
  87213. PhysicsVortexEvent.prototype.enable = function () {
  87214. this._tickCallback.call(this);
  87215. this._scene.registerBeforeRender(this._tickCallback);
  87216. };
  87217. /**
  87218. * Disables the cortex.
  87219. */
  87220. PhysicsVortexEvent.prototype.disable = function () {
  87221. this._scene.unregisterBeforeRender(this._tickCallback);
  87222. };
  87223. /**
  87224. * Disposes the sphere.
  87225. * @param {bolean} force
  87226. */
  87227. PhysicsVortexEvent.prototype.dispose = function (force) {
  87228. var _this = this;
  87229. if (force === void 0) { force = true; }
  87230. if (force) {
  87231. this._cylinder.dispose();
  87232. }
  87233. else {
  87234. setTimeout(function () {
  87235. if (!_this._dataFetched) {
  87236. _this._cylinder.dispose();
  87237. }
  87238. }, 0);
  87239. }
  87240. };
  87241. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  87242. if (impostor.mass === 0) {
  87243. return null;
  87244. }
  87245. if (!this._intersectsWithCylinder(impostor)) {
  87246. return null;
  87247. }
  87248. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  87249. return null;
  87250. }
  87251. var impostorObjectCenter = impostor.getObjectCenter();
  87252. 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)
  87253. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  87254. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  87255. var hit = ray.intersectsMesh(impostor.object);
  87256. var contactPoint = hit.pickedPoint;
  87257. if (!contactPoint) {
  87258. return null;
  87259. }
  87260. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  87261. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  87262. var directionToOrigin = contactPoint.normalize();
  87263. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  87264. directionToOrigin = directionToOrigin.negate();
  87265. }
  87266. // TODO: find a more physically based solution
  87267. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  87268. var forceX = directionToOrigin.x * this._strength / 8;
  87269. var forceY = directionToOrigin.y * this._updraftMultiplier;
  87270. var forceZ = directionToOrigin.z * this._strength / 8;
  87271. }
  87272. else {
  87273. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  87274. var forceY = this._originTop.y * this._updraftMultiplier;
  87275. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  87276. }
  87277. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  87278. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  87279. return { force: force, contactPoint: impostorObjectCenter };
  87280. };
  87281. PhysicsVortexEvent.prototype._tick = function () {
  87282. var _this = this;
  87283. this._physicsEngine.getImpostors().forEach(function (impostor) {
  87284. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  87285. if (!impostorForceAndContactPoint) {
  87286. return;
  87287. }
  87288. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87289. });
  87290. };
  87291. /*** Helpers ***/
  87292. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  87293. if (!this._cylinder) {
  87294. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  87295. height: this._height,
  87296. diameter: this._radius * 2,
  87297. }, this._scene);
  87298. this._cylinder.isVisible = false;
  87299. }
  87300. };
  87301. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  87302. var impostorObject = impostor.object;
  87303. this._prepareCylinder();
  87304. this._cylinder.position = this._cylinderPosition;
  87305. return this._cylinder.intersectsMesh(impostorObject, true);
  87306. };
  87307. return PhysicsVortexEvent;
  87308. }());
  87309. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  87310. /***** Enums *****/
  87311. /**
  87312. * The strenght of the force in correspondence to the distance of the affected object
  87313. */
  87314. var PhysicsRadialImpulseFalloff;
  87315. (function (PhysicsRadialImpulseFalloff) {
  87316. /** Defines that impulse is constant in strength across it's whole radius */
  87317. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  87318. /** DEfines that impulse gets weaker if it's further from the origin */
  87319. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  87320. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  87321. /**
  87322. * The strenght of the force in correspondence to the distance of the affected object
  87323. */
  87324. var PhysicsUpdraftMode;
  87325. (function (PhysicsUpdraftMode) {
  87326. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  87327. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  87328. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  87329. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  87330. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  87331. })(BABYLON || (BABYLON = {}));
  87332. //# sourceMappingURL=babylon.physicsHelper.js.map
  87333. var BABYLON;
  87334. (function (BABYLON) {
  87335. var CannonJSPlugin = /** @class */ (function () {
  87336. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  87337. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  87338. if (iterations === void 0) { iterations = 10; }
  87339. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  87340. this.name = "CannonJSPlugin";
  87341. this._physicsMaterials = new Array();
  87342. this._fixedTimeStep = 1 / 60;
  87343. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  87344. this.BJSCANNON = CANNON;
  87345. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  87346. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  87347. this._tmpPosition = BABYLON.Vector3.Zero();
  87348. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  87349. this._tmpUnityRotation = new BABYLON.Quaternion();
  87350. if (!this.isSupported()) {
  87351. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  87352. return;
  87353. }
  87354. this._extendNamespace();
  87355. this.world = new this.BJSCANNON.World();
  87356. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  87357. this.world.solver.iterations = iterations;
  87358. }
  87359. CannonJSPlugin.prototype.setGravity = function (gravity) {
  87360. this.world.gravity.copy(gravity);
  87361. };
  87362. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  87363. this._fixedTimeStep = timeStep;
  87364. };
  87365. CannonJSPlugin.prototype.getTimeStep = function () {
  87366. return this._fixedTimeStep;
  87367. };
  87368. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  87369. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  87370. };
  87371. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  87372. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  87373. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  87374. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  87375. };
  87376. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  87377. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  87378. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  87379. impostor.physicsBody.applyForce(impulse, worldPoint);
  87380. };
  87381. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  87382. //parent-child relationship. Does this impostor has a parent impostor?
  87383. if (impostor.parent) {
  87384. if (impostor.physicsBody) {
  87385. this.removePhysicsBody(impostor);
  87386. //TODO is that needed?
  87387. impostor.forceUpdate();
  87388. }
  87389. return;
  87390. }
  87391. //should a new body be created for this impostor?
  87392. if (impostor.isBodyInitRequired()) {
  87393. var shape = this._createShape(impostor);
  87394. //unregister events, if body is being changed
  87395. var oldBody = impostor.physicsBody;
  87396. if (oldBody) {
  87397. this.removePhysicsBody(impostor);
  87398. }
  87399. //create the body and material
  87400. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  87401. var bodyCreationObject = {
  87402. mass: impostor.getParam("mass"),
  87403. material: material
  87404. };
  87405. // A simple extend, in case native options were used.
  87406. var nativeOptions = impostor.getParam("nativeOptions");
  87407. for (var key in nativeOptions) {
  87408. if (nativeOptions.hasOwnProperty(key)) {
  87409. bodyCreationObject[key] = nativeOptions[key];
  87410. }
  87411. }
  87412. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  87413. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  87414. this.world.addEventListener("preStep", impostor.beforeStep);
  87415. this.world.addEventListener("postStep", impostor.afterStep);
  87416. impostor.physicsBody.addShape(shape);
  87417. this.world.add(impostor.physicsBody);
  87418. //try to keep the body moving in the right direction by taking old properties.
  87419. //Should be tested!
  87420. if (oldBody) {
  87421. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  87422. impostor.physicsBody[param].copy(oldBody[param]);
  87423. });
  87424. }
  87425. this._processChildMeshes(impostor);
  87426. }
  87427. //now update the body's transformation
  87428. this._updatePhysicsBodyTransformation(impostor);
  87429. };
  87430. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  87431. var _this = this;
  87432. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  87433. var currentRotation = mainImpostor.object.rotationQuaternion;
  87434. if (meshChildren.length) {
  87435. var processMesh = function (localPosition, mesh) {
  87436. if (!currentRotation || !mesh.rotationQuaternion) {
  87437. return;
  87438. }
  87439. var childImpostor = mesh.getPhysicsImpostor();
  87440. if (childImpostor) {
  87441. var parent = childImpostor.parent;
  87442. if (parent !== mainImpostor) {
  87443. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  87444. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  87445. if (childImpostor.physicsBody) {
  87446. _this.removePhysicsBody(childImpostor);
  87447. childImpostor.physicsBody = null;
  87448. }
  87449. childImpostor.parent = mainImpostor;
  87450. childImpostor.resetUpdateFlags();
  87451. 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));
  87452. //Add the mass of the children.
  87453. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  87454. }
  87455. }
  87456. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  87457. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  87458. };
  87459. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  87460. }
  87461. };
  87462. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87463. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  87464. this.world.removeEventListener("preStep", impostor.beforeStep);
  87465. this.world.removeEventListener("postStep", impostor.afterStep);
  87466. this.world.remove(impostor.physicsBody);
  87467. };
  87468. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87469. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87470. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87471. if (!mainBody || !connectedBody) {
  87472. return;
  87473. }
  87474. var constraint;
  87475. var jointData = impostorJoint.joint.jointData;
  87476. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  87477. var constraintData = {
  87478. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  87479. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  87480. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  87481. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  87482. maxForce: jointData.nativeParams.maxForce,
  87483. collideConnected: !!jointData.collision
  87484. };
  87485. switch (impostorJoint.joint.type) {
  87486. case BABYLON.PhysicsJoint.HingeJoint:
  87487. case BABYLON.PhysicsJoint.Hinge2Joint:
  87488. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  87489. break;
  87490. case BABYLON.PhysicsJoint.DistanceJoint:
  87491. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  87492. break;
  87493. case BABYLON.PhysicsJoint.SpringJoint:
  87494. var springData = jointData;
  87495. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  87496. restLength: springData.length,
  87497. stiffness: springData.stiffness,
  87498. damping: springData.damping,
  87499. localAnchorA: constraintData.pivotA,
  87500. localAnchorB: constraintData.pivotB
  87501. });
  87502. break;
  87503. case BABYLON.PhysicsJoint.LockJoint:
  87504. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  87505. break;
  87506. case BABYLON.PhysicsJoint.PointToPointJoint:
  87507. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87508. default:
  87509. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  87510. break;
  87511. }
  87512. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  87513. constraint.collideConnected = !!jointData.collision;
  87514. impostorJoint.joint.physicsJoint = constraint;
  87515. //don't add spring as constraint, as it is not one.
  87516. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  87517. this.world.addConstraint(constraint);
  87518. }
  87519. else {
  87520. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  87521. constraint.applyForce();
  87522. });
  87523. }
  87524. };
  87525. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87526. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  87527. };
  87528. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  87529. var index;
  87530. var mat;
  87531. for (index = 0; index < this._physicsMaterials.length; index++) {
  87532. mat = this._physicsMaterials[index];
  87533. if (mat.friction === friction && mat.restitution === restitution) {
  87534. return mat;
  87535. }
  87536. }
  87537. var currentMat = new this.BJSCANNON.Material(name);
  87538. currentMat.friction = friction;
  87539. currentMat.restitution = restitution;
  87540. this._physicsMaterials.push(currentMat);
  87541. return currentMat;
  87542. };
  87543. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  87544. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  87545. };
  87546. CannonJSPlugin.prototype._createShape = function (impostor) {
  87547. var object = impostor.object;
  87548. var returnValue;
  87549. var extendSize = impostor.getObjectExtendSize();
  87550. switch (impostor.type) {
  87551. case BABYLON.PhysicsImpostor.SphereImpostor:
  87552. var radiusX = extendSize.x;
  87553. var radiusY = extendSize.y;
  87554. var radiusZ = extendSize.z;
  87555. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  87556. break;
  87557. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  87558. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87559. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  87560. break;
  87561. case BABYLON.PhysicsImpostor.BoxImpostor:
  87562. var box = extendSize.scale(0.5);
  87563. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  87564. break;
  87565. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87566. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  87567. returnValue = new this.BJSCANNON.Plane();
  87568. break;
  87569. case BABYLON.PhysicsImpostor.MeshImpostor:
  87570. // should transform the vertex data to world coordinates!!
  87571. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  87572. var rawFaces = object.getIndices ? object.getIndices() : [];
  87573. if (!rawVerts)
  87574. return;
  87575. // get only scale! so the object could transform correctly.
  87576. var oldPosition = object.position.clone();
  87577. var oldRotation = object.rotation && object.rotation.clone();
  87578. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  87579. object.position.copyFromFloats(0, 0, 0);
  87580. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87581. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87582. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87583. var transform = object.computeWorldMatrix(true);
  87584. // convert rawVerts to object space
  87585. var temp = new Array();
  87586. var index;
  87587. for (index = 0; index < rawVerts.length; index += 3) {
  87588. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  87589. }
  87590. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  87591. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  87592. //now set back the transformation!
  87593. object.position.copyFrom(oldPosition);
  87594. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  87595. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  87596. break;
  87597. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  87598. var oldPosition2 = object.position.clone();
  87599. var oldRotation2 = object.rotation && object.rotation.clone();
  87600. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  87601. object.position.copyFromFloats(0, 0, 0);
  87602. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87603. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87604. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87605. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  87606. returnValue = this._createHeightmap(object);
  87607. object.position.copyFrom(oldPosition2);
  87608. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  87609. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  87610. object.computeWorldMatrix(true);
  87611. break;
  87612. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87613. returnValue = new this.BJSCANNON.Particle();
  87614. break;
  87615. }
  87616. return returnValue;
  87617. };
  87618. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  87619. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  87620. var transform = object.computeWorldMatrix(true);
  87621. // convert rawVerts to object space
  87622. var temp = new Array();
  87623. var index;
  87624. for (index = 0; index < pos.length; index += 3) {
  87625. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  87626. }
  87627. pos = temp;
  87628. var matrix = new Array();
  87629. //For now pointDepth will not be used and will be automatically calculated.
  87630. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  87631. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  87632. var boundingInfo = object.getBoundingInfo();
  87633. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  87634. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  87635. var elementSize = dim * 2 / arraySize;
  87636. for (var i = 0; i < pos.length; i = i + 3) {
  87637. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  87638. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  87639. var y = -pos[i + 2] + minY;
  87640. if (!matrix[x]) {
  87641. matrix[x] = [];
  87642. }
  87643. if (!matrix[x][z]) {
  87644. matrix[x][z] = y;
  87645. }
  87646. matrix[x][z] = Math.max(y, matrix[x][z]);
  87647. }
  87648. for (var x = 0; x <= arraySize; ++x) {
  87649. if (!matrix[x]) {
  87650. var loc = 1;
  87651. while (!matrix[(x + loc) % arraySize]) {
  87652. loc++;
  87653. }
  87654. matrix[x] = matrix[(x + loc) % arraySize].slice();
  87655. //console.log("missing x", x);
  87656. }
  87657. for (var z = 0; z <= arraySize; ++z) {
  87658. if (!matrix[x][z]) {
  87659. var loc = 1;
  87660. var newValue;
  87661. while (newValue === undefined) {
  87662. newValue = matrix[x][(z + loc++) % arraySize];
  87663. }
  87664. matrix[x][z] = newValue;
  87665. }
  87666. }
  87667. }
  87668. var shape = new this.BJSCANNON.Heightfield(matrix, {
  87669. elementSize: elementSize
  87670. });
  87671. //For future reference, needed for body transformation
  87672. shape.minY = minY;
  87673. return shape;
  87674. };
  87675. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  87676. var object = impostor.object;
  87677. //make sure it is updated...
  87678. object.computeWorldMatrix && object.computeWorldMatrix(true);
  87679. // The delta between the mesh position and the mesh bounding box center
  87680. var bInfo = object.getBoundingInfo();
  87681. if (!bInfo)
  87682. return;
  87683. var center = impostor.getObjectCenter();
  87684. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  87685. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  87686. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  87687. this._tmpPosition.copyFrom(center);
  87688. var quaternion = object.rotationQuaternion;
  87689. if (!quaternion) {
  87690. return;
  87691. }
  87692. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  87693. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  87694. //-90 DEG in X, precalculated
  87695. quaternion = quaternion.multiply(this._minus90X);
  87696. //Invert! (Precalculated, 90 deg in X)
  87697. //No need to clone. this will never change.
  87698. impostor.setDeltaRotation(this._plus90X);
  87699. }
  87700. //If it is a heightfield, if should be centered.
  87701. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  87702. var mesh = object;
  87703. var boundingInfo = mesh.getBoundingInfo();
  87704. //calculate the correct body position:
  87705. var rotationQuaternion = mesh.rotationQuaternion;
  87706. mesh.rotationQuaternion = this._tmpUnityRotation;
  87707. mesh.computeWorldMatrix(true);
  87708. //get original center with no rotation
  87709. var c = center.clone();
  87710. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  87711. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  87712. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  87713. mesh.setPreTransformMatrix(p);
  87714. mesh.computeWorldMatrix(true);
  87715. //calculate the translation
  87716. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  87717. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  87718. //add it inverted to the delta
  87719. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  87720. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  87721. //rotation is back
  87722. mesh.rotationQuaternion = rotationQuaternion;
  87723. mesh.setPreTransformMatrix(oldPivot);
  87724. mesh.computeWorldMatrix(true);
  87725. }
  87726. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  87727. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  87728. //this._tmpPosition.copyFrom(object.position);
  87729. }
  87730. impostor.setDeltaPosition(this._tmpDeltaPosition);
  87731. //Now update the impostor object
  87732. impostor.physicsBody.position.copy(this._tmpPosition);
  87733. impostor.physicsBody.quaternion.copy(quaternion);
  87734. };
  87735. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87736. impostor.object.position.copyFrom(impostor.physicsBody.position);
  87737. if (impostor.object.rotationQuaternion) {
  87738. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  87739. }
  87740. };
  87741. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87742. impostor.physicsBody.position.copy(newPosition);
  87743. impostor.physicsBody.quaternion.copy(newRotation);
  87744. };
  87745. CannonJSPlugin.prototype.isSupported = function () {
  87746. return this.BJSCANNON !== undefined;
  87747. };
  87748. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87749. impostor.physicsBody.velocity.copy(velocity);
  87750. };
  87751. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87752. impostor.physicsBody.angularVelocity.copy(velocity);
  87753. };
  87754. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87755. var v = impostor.physicsBody.velocity;
  87756. if (!v) {
  87757. return null;
  87758. }
  87759. return new BABYLON.Vector3(v.x, v.y, v.z);
  87760. };
  87761. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87762. var v = impostor.physicsBody.angularVelocity;
  87763. if (!v) {
  87764. return null;
  87765. }
  87766. return new BABYLON.Vector3(v.x, v.y, v.z);
  87767. };
  87768. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87769. impostor.physicsBody.mass = mass;
  87770. impostor.physicsBody.updateMassProperties();
  87771. };
  87772. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  87773. return impostor.physicsBody.mass;
  87774. };
  87775. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  87776. return impostor.physicsBody.material.friction;
  87777. };
  87778. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87779. impostor.physicsBody.material.friction = friction;
  87780. };
  87781. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87782. return impostor.physicsBody.material.restitution;
  87783. };
  87784. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87785. impostor.physicsBody.material.restitution = restitution;
  87786. };
  87787. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  87788. impostor.physicsBody.sleep();
  87789. };
  87790. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  87791. impostor.physicsBody.wakeUp();
  87792. };
  87793. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87794. joint.physicsJoint.distance = maxDistance;
  87795. };
  87796. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87797. // if (!motorIndex) {
  87798. // joint.physicsJoint.enableMotor();
  87799. // }
  87800. // }
  87801. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  87802. // if (!motorIndex) {
  87803. // joint.physicsJoint.disableMotor();
  87804. // }
  87805. // }
  87806. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87807. if (!motorIndex) {
  87808. joint.physicsJoint.enableMotor();
  87809. joint.physicsJoint.setMotorSpeed(speed);
  87810. if (maxForce) {
  87811. this.setLimit(joint, maxForce);
  87812. }
  87813. }
  87814. };
  87815. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  87816. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  87817. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  87818. };
  87819. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87820. var body = impostor.physicsBody;
  87821. mesh.position.x = body.position.x;
  87822. mesh.position.y = body.position.y;
  87823. mesh.position.z = body.position.z;
  87824. if (mesh.rotationQuaternion) {
  87825. mesh.rotationQuaternion.x = body.quaternion.x;
  87826. mesh.rotationQuaternion.y = body.quaternion.y;
  87827. mesh.rotationQuaternion.z = body.quaternion.z;
  87828. mesh.rotationQuaternion.w = body.quaternion.w;
  87829. }
  87830. };
  87831. CannonJSPlugin.prototype.getRadius = function (impostor) {
  87832. var shape = impostor.physicsBody.shapes[0];
  87833. return shape.boundingSphereRadius;
  87834. };
  87835. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87836. var shape = impostor.physicsBody.shapes[0];
  87837. result.x = shape.halfExtents.x * 2;
  87838. result.y = shape.halfExtents.y * 2;
  87839. result.z = shape.halfExtents.z * 2;
  87840. };
  87841. CannonJSPlugin.prototype.dispose = function () {
  87842. };
  87843. CannonJSPlugin.prototype._extendNamespace = function () {
  87844. //this will force cannon to execute at least one step when using interpolation
  87845. var step_tmp1 = new this.BJSCANNON.Vec3();
  87846. var Engine = this.BJSCANNON;
  87847. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  87848. maxSubSteps = maxSubSteps || 10;
  87849. timeSinceLastCalled = timeSinceLastCalled || 0;
  87850. if (timeSinceLastCalled === 0) {
  87851. this.internalStep(dt);
  87852. this.time += dt;
  87853. }
  87854. else {
  87855. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  87856. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  87857. var t0 = performance.now();
  87858. for (var i = 0; i !== internalSteps; i++) {
  87859. this.internalStep(dt);
  87860. if (performance.now() - t0 > dt * 1000) {
  87861. break;
  87862. }
  87863. }
  87864. this.time += timeSinceLastCalled;
  87865. var h = this.time % dt;
  87866. var h_div_dt = h / dt;
  87867. var interpvelo = step_tmp1;
  87868. var bodies = this.bodies;
  87869. for (var j = 0; j !== bodies.length; j++) {
  87870. var b = bodies[j];
  87871. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  87872. b.position.vsub(b.previousPosition, interpvelo);
  87873. interpvelo.scale(h_div_dt, interpvelo);
  87874. b.position.vadd(interpvelo, b.interpolatedPosition);
  87875. }
  87876. else {
  87877. b.interpolatedPosition.copy(b.position);
  87878. b.interpolatedQuaternion.copy(b.quaternion);
  87879. }
  87880. }
  87881. }
  87882. };
  87883. };
  87884. return CannonJSPlugin;
  87885. }());
  87886. BABYLON.CannonJSPlugin = CannonJSPlugin;
  87887. })(BABYLON || (BABYLON = {}));
  87888. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  87889. var BABYLON;
  87890. (function (BABYLON) {
  87891. var OimoJSPlugin = /** @class */ (function () {
  87892. function OimoJSPlugin(iterations) {
  87893. this.name = "OimoJSPlugin";
  87894. this._tmpImpostorsArray = [];
  87895. this._tmpPositionVector = BABYLON.Vector3.Zero();
  87896. this.BJSOIMO = OIMO;
  87897. this.world = new this.BJSOIMO.World({
  87898. iterations: iterations
  87899. });
  87900. this.world.clear();
  87901. }
  87902. OimoJSPlugin.prototype.setGravity = function (gravity) {
  87903. this.world.gravity.copy(gravity);
  87904. };
  87905. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  87906. this.world.timeStep = timeStep;
  87907. };
  87908. OimoJSPlugin.prototype.getTimeStep = function () {
  87909. return this.world.timeStep;
  87910. };
  87911. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  87912. var _this = this;
  87913. impostors.forEach(function (impostor) {
  87914. impostor.beforeStep();
  87915. });
  87916. this.world.step();
  87917. impostors.forEach(function (impostor) {
  87918. impostor.afterStep();
  87919. //update the ordered impostors array
  87920. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  87921. });
  87922. //check for collisions
  87923. var contact = this.world.contacts;
  87924. while (contact !== null) {
  87925. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  87926. contact = contact.next;
  87927. continue;
  87928. }
  87929. //is this body colliding with any other? get the impostor
  87930. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  87931. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  87932. if (!mainImpostor || !collidingImpostor) {
  87933. contact = contact.next;
  87934. continue;
  87935. }
  87936. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  87937. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  87938. contact = contact.next;
  87939. }
  87940. };
  87941. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  87942. var mass = impostor.physicsBody.mass;
  87943. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  87944. };
  87945. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  87946. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  87947. this.applyImpulse(impostor, force, contactPoint);
  87948. };
  87949. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  87950. var _this = this;
  87951. //parent-child relationship. Does this impostor has a parent impostor?
  87952. if (impostor.parent) {
  87953. if (impostor.physicsBody) {
  87954. this.removePhysicsBody(impostor);
  87955. //TODO is that needed?
  87956. impostor.forceUpdate();
  87957. }
  87958. return;
  87959. }
  87960. if (impostor.isBodyInitRequired()) {
  87961. var bodyConfig = {
  87962. name: impostor.uniqueId,
  87963. //Oimo must have mass, also for static objects.
  87964. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  87965. size: [],
  87966. type: [],
  87967. pos: [],
  87968. posShape: [],
  87969. rot: [],
  87970. rotShape: [],
  87971. move: impostor.getParam("mass") !== 0,
  87972. density: impostor.getParam("mass"),
  87973. friction: impostor.getParam("friction"),
  87974. restitution: impostor.getParam("restitution"),
  87975. //Supporting older versions of Oimo
  87976. world: this.world
  87977. };
  87978. var impostors = [impostor];
  87979. var addToArray = function (parent) {
  87980. if (!parent.getChildMeshes)
  87981. return;
  87982. parent.getChildMeshes().forEach(function (m) {
  87983. if (m.physicsImpostor) {
  87984. impostors.push(m.physicsImpostor);
  87985. //m.physicsImpostor._init();
  87986. }
  87987. });
  87988. };
  87989. addToArray(impostor.object);
  87990. var checkWithEpsilon_1 = function (value) {
  87991. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  87992. };
  87993. var globalQuaternion_1 = new BABYLON.Quaternion();
  87994. impostors.forEach(function (i) {
  87995. if (!i.object.rotationQuaternion) {
  87996. return;
  87997. }
  87998. //get the correct bounding box
  87999. var oldQuaternion = i.object.rotationQuaternion;
  88000. globalQuaternion_1 = oldQuaternion.clone();
  88001. var rot = oldQuaternion.toEulerAngles();
  88002. var extendSize = i.getObjectExtendSize();
  88003. var radToDeg = 57.295779513082320876;
  88004. if (i === impostor) {
  88005. var center = impostor.getObjectCenter();
  88006. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  88007. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  88008. //Can also use Array.prototype.push.apply
  88009. bodyConfig.pos.push(center.x);
  88010. bodyConfig.pos.push(center.y);
  88011. bodyConfig.pos.push(center.z);
  88012. bodyConfig.posShape.push(0, 0, 0);
  88013. //tmp solution
  88014. bodyConfig.rot.push(0);
  88015. bodyConfig.rot.push(0);
  88016. bodyConfig.rot.push(0);
  88017. bodyConfig.rotShape.push(0, 0, 0);
  88018. }
  88019. else {
  88020. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  88021. bodyConfig.posShape.push(localPosition.x);
  88022. bodyConfig.posShape.push(localPosition.y);
  88023. bodyConfig.posShape.push(localPosition.z);
  88024. bodyConfig.pos.push(0, 0, 0);
  88025. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  88026. bodyConfig.rot.push(0);
  88027. bodyConfig.rot.push(0);
  88028. bodyConfig.rot.push(0);
  88029. bodyConfig.rotShape.push(rot.x * radToDeg);
  88030. bodyConfig.rotShape.push(rot.y * radToDeg);
  88031. bodyConfig.rotShape.push(rot.z * radToDeg);
  88032. }
  88033. // register mesh
  88034. switch (i.type) {
  88035. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88036. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  88037. case BABYLON.PhysicsImpostor.SphereImpostor:
  88038. var radiusX = extendSize.x;
  88039. var radiusY = extendSize.y;
  88040. var radiusZ = extendSize.z;
  88041. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  88042. bodyConfig.type.push('sphere');
  88043. //due to the way oimo works with compounds, add 3 times
  88044. bodyConfig.size.push(size);
  88045. bodyConfig.size.push(size);
  88046. bodyConfig.size.push(size);
  88047. break;
  88048. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88049. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  88050. var sizeY = checkWithEpsilon_1(extendSize.y);
  88051. bodyConfig.type.push('cylinder');
  88052. bodyConfig.size.push(sizeX);
  88053. bodyConfig.size.push(sizeY);
  88054. //due to the way oimo works with compounds, add one more value.
  88055. bodyConfig.size.push(sizeY);
  88056. break;
  88057. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88058. case BABYLON.PhysicsImpostor.BoxImpostor:
  88059. default:
  88060. var sizeX = checkWithEpsilon_1(extendSize.x);
  88061. var sizeY = checkWithEpsilon_1(extendSize.y);
  88062. var sizeZ = checkWithEpsilon_1(extendSize.z);
  88063. bodyConfig.type.push('box');
  88064. //if (i === impostor) {
  88065. bodyConfig.size.push(sizeX);
  88066. bodyConfig.size.push(sizeY);
  88067. bodyConfig.size.push(sizeZ);
  88068. //} else {
  88069. // bodyConfig.size.push(0,0,0);
  88070. //}
  88071. break;
  88072. }
  88073. //actually not needed, but hey...
  88074. i.object.rotationQuaternion = oldQuaternion;
  88075. });
  88076. impostor.physicsBody = this.world.add(bodyConfig);
  88077. // set the quaternion, ignoring the previously defined (euler) rotation
  88078. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  88079. // update with delta 0, so the body will reveive the new rotation.
  88080. impostor.physicsBody.updatePosition(0);
  88081. }
  88082. else {
  88083. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  88084. }
  88085. impostor.setDeltaPosition(this._tmpPositionVector);
  88086. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  88087. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  88088. };
  88089. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88090. //impostor.physicsBody.dispose();
  88091. //Same as : (older oimo versions)
  88092. this.world.removeRigidBody(impostor.physicsBody);
  88093. };
  88094. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88095. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88096. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88097. if (!mainBody || !connectedBody) {
  88098. return;
  88099. }
  88100. var jointData = impostorJoint.joint.jointData;
  88101. var options = jointData.nativeParams || {};
  88102. var type;
  88103. var nativeJointData = {
  88104. body1: mainBody,
  88105. body2: connectedBody,
  88106. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  88107. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  88108. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  88109. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  88110. min: options.min,
  88111. max: options.max,
  88112. collision: options.collision || jointData.collision,
  88113. spring: options.spring,
  88114. //supporting older version of Oimo
  88115. world: this.world
  88116. };
  88117. switch (impostorJoint.joint.type) {
  88118. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88119. type = "jointBall";
  88120. break;
  88121. case BABYLON.PhysicsJoint.SpringJoint:
  88122. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  88123. var springData = jointData;
  88124. nativeJointData.min = springData.length || nativeJointData.min;
  88125. //Max should also be set, just make sure it is at least min
  88126. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  88127. case BABYLON.PhysicsJoint.DistanceJoint:
  88128. type = "jointDistance";
  88129. nativeJointData.max = jointData.maxDistance;
  88130. break;
  88131. case BABYLON.PhysicsJoint.PrismaticJoint:
  88132. type = "jointPrisme";
  88133. break;
  88134. case BABYLON.PhysicsJoint.SliderJoint:
  88135. type = "jointSlide";
  88136. break;
  88137. case BABYLON.PhysicsJoint.WheelJoint:
  88138. type = "jointWheel";
  88139. break;
  88140. case BABYLON.PhysicsJoint.HingeJoint:
  88141. default:
  88142. type = "jointHinge";
  88143. break;
  88144. }
  88145. nativeJointData.type = type;
  88146. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  88147. };
  88148. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88149. //Bug in Oimo prevents us from disposing a joint in the playground
  88150. //joint.joint.physicsJoint.dispose();
  88151. //So we will bruteforce it!
  88152. try {
  88153. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  88154. }
  88155. catch (e) {
  88156. BABYLON.Tools.Warn(e);
  88157. }
  88158. };
  88159. OimoJSPlugin.prototype.isSupported = function () {
  88160. return this.BJSOIMO !== undefined;
  88161. };
  88162. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88163. if (!impostor.physicsBody.sleeping) {
  88164. //TODO check that
  88165. /*if (impostor.physicsBody.shapes.next) {
  88166. var parentShape = this._getLastShape(impostor.physicsBody);
  88167. impostor.object.position.copyFrom(parentShape.position);
  88168. console.log(parentShape.position);
  88169. } else {*/
  88170. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  88171. //}
  88172. if (impostor.object.rotationQuaternion) {
  88173. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  88174. }
  88175. }
  88176. };
  88177. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88178. var body = impostor.physicsBody;
  88179. body.position.copy(newPosition);
  88180. body.orientation.copy(newRotation);
  88181. body.syncShapes();
  88182. body.awake();
  88183. };
  88184. /*private _getLastShape(body: any): any {
  88185. var lastShape = body.shapes;
  88186. while (lastShape.next) {
  88187. lastShape = lastShape.next;
  88188. }
  88189. return lastShape;
  88190. }*/
  88191. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88192. impostor.physicsBody.linearVelocity.copy(velocity);
  88193. };
  88194. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88195. impostor.physicsBody.angularVelocity.copy(velocity);
  88196. };
  88197. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88198. var v = impostor.physicsBody.linearVelocity;
  88199. if (!v) {
  88200. return null;
  88201. }
  88202. return new BABYLON.Vector3(v.x, v.y, v.z);
  88203. };
  88204. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88205. var v = impostor.physicsBody.angularVelocity;
  88206. if (!v) {
  88207. return null;
  88208. }
  88209. return new BABYLON.Vector3(v.x, v.y, v.z);
  88210. };
  88211. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88212. var staticBody = mass === 0;
  88213. //this will actually set the body's density and not its mass.
  88214. //But this is how oimo treats the mass variable.
  88215. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  88216. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  88217. };
  88218. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  88219. return impostor.physicsBody.shapes.density;
  88220. };
  88221. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  88222. return impostor.physicsBody.shapes.friction;
  88223. };
  88224. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  88225. impostor.physicsBody.shapes.friction = friction;
  88226. };
  88227. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  88228. return impostor.physicsBody.shapes.restitution;
  88229. };
  88230. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  88231. impostor.physicsBody.shapes.restitution = restitution;
  88232. };
  88233. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  88234. impostor.physicsBody.sleep();
  88235. };
  88236. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  88237. impostor.physicsBody.awake();
  88238. };
  88239. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  88240. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  88241. if (minDistance !== void 0) {
  88242. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  88243. }
  88244. };
  88245. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  88246. //TODO separate rotational and transational motors.
  88247. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  88248. if (motor) {
  88249. motor.setMotor(speed, maxForce);
  88250. }
  88251. };
  88252. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  88253. //TODO separate rotational and transational motors.
  88254. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  88255. if (motor) {
  88256. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  88257. }
  88258. };
  88259. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  88260. var body = impostor.physicsBody;
  88261. mesh.position.x = body.position.x;
  88262. mesh.position.y = body.position.y;
  88263. mesh.position.z = body.position.z;
  88264. if (mesh.rotationQuaternion) {
  88265. mesh.rotationQuaternion.x = body.orientation.x;
  88266. mesh.rotationQuaternion.y = body.orientation.y;
  88267. mesh.rotationQuaternion.z = body.orientation.z;
  88268. mesh.rotationQuaternion.w = body.orientation.s;
  88269. }
  88270. };
  88271. OimoJSPlugin.prototype.getRadius = function (impostor) {
  88272. return impostor.physicsBody.shapes.radius;
  88273. };
  88274. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  88275. var shape = impostor.physicsBody.shapes;
  88276. result.x = shape.halfWidth * 2;
  88277. result.y = shape.halfHeight * 2;
  88278. result.z = shape.halfDepth * 2;
  88279. };
  88280. OimoJSPlugin.prototype.dispose = function () {
  88281. this.world.clear();
  88282. };
  88283. return OimoJSPlugin;
  88284. }());
  88285. BABYLON.OimoJSPlugin = OimoJSPlugin;
  88286. })(BABYLON || (BABYLON = {}));
  88287. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  88288. var BABYLON;
  88289. (function (BABYLON) {
  88290. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  88291. // All values and structures referenced from:
  88292. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  88293. var DDS_MAGIC = 0x20534444;
  88294. var
  88295. //DDSD_CAPS = 0x1,
  88296. //DDSD_HEIGHT = 0x2,
  88297. //DDSD_WIDTH = 0x4,
  88298. //DDSD_PITCH = 0x8,
  88299. //DDSD_PIXELFORMAT = 0x1000,
  88300. DDSD_MIPMAPCOUNT = 0x20000;
  88301. //DDSD_LINEARSIZE = 0x80000,
  88302. //DDSD_DEPTH = 0x800000;
  88303. // var DDSCAPS_COMPLEX = 0x8,
  88304. // DDSCAPS_MIPMAP = 0x400000,
  88305. // DDSCAPS_TEXTURE = 0x1000;
  88306. var DDSCAPS2_CUBEMAP = 0x200;
  88307. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  88308. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  88309. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  88310. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  88311. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  88312. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  88313. // DDSCAPS2_VOLUME = 0x200000;
  88314. var
  88315. //DDPF_ALPHAPIXELS = 0x1,
  88316. //DDPF_ALPHA = 0x2,
  88317. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  88318. //DDPF_YUV = 0x200,
  88319. DDPF_LUMINANCE = 0x20000;
  88320. function FourCCToInt32(value) {
  88321. return value.charCodeAt(0) +
  88322. (value.charCodeAt(1) << 8) +
  88323. (value.charCodeAt(2) << 16) +
  88324. (value.charCodeAt(3) << 24);
  88325. }
  88326. function Int32ToFourCC(value) {
  88327. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  88328. }
  88329. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  88330. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  88331. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  88332. var FOURCC_DX10 = FourCCToInt32("DX10");
  88333. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  88334. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  88335. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  88336. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  88337. var headerLengthInt = 31; // The header length in 32 bit ints
  88338. // Offsets into the header array
  88339. var off_magic = 0;
  88340. var off_size = 1;
  88341. var off_flags = 2;
  88342. var off_height = 3;
  88343. var off_width = 4;
  88344. var off_mipmapCount = 7;
  88345. var off_pfFlags = 20;
  88346. var off_pfFourCC = 21;
  88347. var off_RGBbpp = 22;
  88348. var off_RMask = 23;
  88349. var off_GMask = 24;
  88350. var off_BMask = 25;
  88351. var off_AMask = 26;
  88352. // var off_caps1 = 27;
  88353. var off_caps2 = 28;
  88354. // var off_caps3 = 29;
  88355. // var off_caps4 = 30;
  88356. var off_dxgiFormat = 32;
  88357. ;
  88358. var DDSTools = /** @class */ (function () {
  88359. function DDSTools() {
  88360. }
  88361. DDSTools.GetDDSInfo = function (arrayBuffer) {
  88362. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88363. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  88364. var mipmapCount = 1;
  88365. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  88366. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88367. }
  88368. var fourCC = header[off_pfFourCC];
  88369. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  88370. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88371. switch (fourCC) {
  88372. case FOURCC_D3DFMT_R16G16B16A16F:
  88373. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88374. break;
  88375. case FOURCC_D3DFMT_R32G32B32A32F:
  88376. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88377. break;
  88378. case FOURCC_DX10:
  88379. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  88380. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88381. break;
  88382. }
  88383. }
  88384. return {
  88385. width: header[off_width],
  88386. height: header[off_height],
  88387. mipmapCount: mipmapCount,
  88388. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  88389. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  88390. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  88391. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  88392. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  88393. dxgiFormat: dxgiFormat,
  88394. textureType: textureType
  88395. };
  88396. };
  88397. DDSTools._ToHalfFloat = function (value) {
  88398. if (!DDSTools._FloatView) {
  88399. DDSTools._FloatView = new Float32Array(1);
  88400. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  88401. }
  88402. DDSTools._FloatView[0] = value;
  88403. var x = DDSTools._Int32View[0];
  88404. var bits = (x >> 16) & 0x8000; /* Get the sign */
  88405. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  88406. var e = (x >> 23) & 0xff; /* Using int is faster here */
  88407. /* If zero, or denormal, or exponent underflows too much for a denormal
  88408. * half, return signed zero. */
  88409. if (e < 103) {
  88410. return bits;
  88411. }
  88412. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  88413. if (e > 142) {
  88414. bits |= 0x7c00;
  88415. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  88416. * not Inf, so make sure we set one mantissa bit too. */
  88417. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  88418. return bits;
  88419. }
  88420. /* If exponent underflows but not too much, return a denormal */
  88421. if (e < 113) {
  88422. m |= 0x0800;
  88423. /* Extra rounding may overflow and set mantissa to 0 and exponent
  88424. * to 1, which is OK. */
  88425. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  88426. return bits;
  88427. }
  88428. bits |= ((e - 112) << 10) | (m >> 1);
  88429. bits += m & 1;
  88430. return bits;
  88431. };
  88432. DDSTools._FromHalfFloat = function (value) {
  88433. var s = (value & 0x8000) >> 15;
  88434. var e = (value & 0x7C00) >> 10;
  88435. var f = value & 0x03FF;
  88436. if (e === 0) {
  88437. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  88438. }
  88439. else if (e == 0x1F) {
  88440. return f ? NaN : ((s ? -1 : 1) * Infinity);
  88441. }
  88442. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  88443. };
  88444. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88445. var destArray = new Float32Array(dataLength);
  88446. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88447. var index = 0;
  88448. for (var y = 0; y < height; y++) {
  88449. for (var x = 0; x < width; x++) {
  88450. var srcPos = (x + y * width) * 4;
  88451. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  88452. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  88453. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  88454. if (DDSTools.StoreLODInAlphaChannel) {
  88455. destArray[index + 3] = lod;
  88456. }
  88457. else {
  88458. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  88459. }
  88460. index += 4;
  88461. }
  88462. }
  88463. return destArray;
  88464. };
  88465. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88466. if (DDSTools.StoreLODInAlphaChannel) {
  88467. var destArray = new Uint16Array(dataLength);
  88468. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88469. var index = 0;
  88470. for (var y = 0; y < height; y++) {
  88471. for (var x = 0; x < width; x++) {
  88472. var srcPos = (x + y * width) * 4;
  88473. destArray[index] = srcData[srcPos];
  88474. destArray[index + 1] = srcData[srcPos + 1];
  88475. destArray[index + 2] = srcData[srcPos + 2];
  88476. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  88477. index += 4;
  88478. }
  88479. }
  88480. return destArray;
  88481. }
  88482. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  88483. };
  88484. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88485. if (DDSTools.StoreLODInAlphaChannel) {
  88486. var destArray = new Float32Array(dataLength);
  88487. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88488. var index = 0;
  88489. for (var y = 0; y < height; y++) {
  88490. for (var x = 0; x < width; x++) {
  88491. var srcPos = (x + y * width) * 4;
  88492. destArray[index] = srcData[srcPos];
  88493. destArray[index + 1] = srcData[srcPos + 1];
  88494. destArray[index + 2] = srcData[srcPos + 2];
  88495. destArray[index + 3] = lod;
  88496. index += 4;
  88497. }
  88498. }
  88499. return destArray;
  88500. }
  88501. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  88502. };
  88503. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88504. var destArray = new Uint8Array(dataLength);
  88505. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88506. var index = 0;
  88507. for (var y = 0; y < height; y++) {
  88508. for (var x = 0; x < width; x++) {
  88509. var srcPos = (x + y * width) * 4;
  88510. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  88511. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  88512. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  88513. if (DDSTools.StoreLODInAlphaChannel) {
  88514. destArray[index + 3] = lod;
  88515. }
  88516. else {
  88517. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  88518. }
  88519. index += 4;
  88520. }
  88521. }
  88522. return destArray;
  88523. };
  88524. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88525. var destArray = new Uint8Array(dataLength);
  88526. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88527. var index = 0;
  88528. for (var y = 0; y < height; y++) {
  88529. for (var x = 0; x < width; x++) {
  88530. var srcPos = (x + y * width) * 4;
  88531. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  88532. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  88533. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  88534. if (DDSTools.StoreLODInAlphaChannel) {
  88535. destArray[index + 3] = lod;
  88536. }
  88537. else {
  88538. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  88539. }
  88540. index += 4;
  88541. }
  88542. }
  88543. return destArray;
  88544. };
  88545. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  88546. var byteArray = new Uint8Array(dataLength);
  88547. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88548. var index = 0;
  88549. for (var y = 0; y < height; y++) {
  88550. for (var x = 0; x < width; x++) {
  88551. var srcPos = (x + y * width) * 4;
  88552. byteArray[index] = srcData[srcPos + rOffset];
  88553. byteArray[index + 1] = srcData[srcPos + gOffset];
  88554. byteArray[index + 2] = srcData[srcPos + bOffset];
  88555. byteArray[index + 3] = srcData[srcPos + aOffset];
  88556. index += 4;
  88557. }
  88558. }
  88559. return byteArray;
  88560. };
  88561. DDSTools._ExtractLongWordOrder = function (value) {
  88562. if (value === 0 || value === 255 || value === -16777216) {
  88563. return 0;
  88564. }
  88565. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  88566. };
  88567. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  88568. var byteArray = new Uint8Array(dataLength);
  88569. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88570. var index = 0;
  88571. for (var y = 0; y < height; y++) {
  88572. for (var x = 0; x < width; x++) {
  88573. var srcPos = (x + y * width) * 3;
  88574. byteArray[index] = srcData[srcPos + rOffset];
  88575. byteArray[index + 1] = srcData[srcPos + gOffset];
  88576. byteArray[index + 2] = srcData[srcPos + bOffset];
  88577. index += 3;
  88578. }
  88579. }
  88580. return byteArray;
  88581. };
  88582. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  88583. var byteArray = new Uint8Array(dataLength);
  88584. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88585. var index = 0;
  88586. for (var y = 0; y < height; y++) {
  88587. for (var x = 0; x < width; x++) {
  88588. var srcPos = (x + y * width);
  88589. byteArray[index] = srcData[srcPos];
  88590. index++;
  88591. }
  88592. }
  88593. return byteArray;
  88594. };
  88595. /**
  88596. * Uploads DDS Levels to a Babylon Texture
  88597. * @hidden
  88598. */
  88599. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  88600. if (lodIndex === void 0) { lodIndex = -1; }
  88601. var sphericalPolynomialFaces = null;
  88602. if (info.sphericalPolynomial) {
  88603. sphericalPolynomialFaces = new Array();
  88604. }
  88605. var ext = engine.getCaps().s3tc;
  88606. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88607. var fourCC, width, height, dataLength = 0, dataOffset;
  88608. var byteArray, mipmapCount, mip;
  88609. var internalCompressedFormat = 0;
  88610. var blockBytes = 1;
  88611. if (header[off_magic] !== DDS_MAGIC) {
  88612. BABYLON.Tools.Error("Invalid magic number in DDS header");
  88613. return;
  88614. }
  88615. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  88616. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  88617. return;
  88618. }
  88619. if (info.isCompressed && !ext) {
  88620. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  88621. return;
  88622. }
  88623. var bpp = header[off_RGBbpp];
  88624. dataOffset = header[off_size] + 4;
  88625. var computeFormats = false;
  88626. if (info.isFourCC) {
  88627. fourCC = header[off_pfFourCC];
  88628. switch (fourCC) {
  88629. case FOURCC_DXT1:
  88630. blockBytes = 8;
  88631. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  88632. break;
  88633. case FOURCC_DXT3:
  88634. blockBytes = 16;
  88635. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  88636. break;
  88637. case FOURCC_DXT5:
  88638. blockBytes = 16;
  88639. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  88640. break;
  88641. case FOURCC_D3DFMT_R16G16B16A16F:
  88642. computeFormats = true;
  88643. break;
  88644. case FOURCC_D3DFMT_R32G32B32A32F:
  88645. computeFormats = true;
  88646. break;
  88647. case FOURCC_DX10:
  88648. // There is an additionnal header so dataOffset need to be changed
  88649. dataOffset += 5 * 4; // 5 uints
  88650. var supported = false;
  88651. switch (info.dxgiFormat) {
  88652. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  88653. computeFormats = true;
  88654. supported = true;
  88655. break;
  88656. case DXGI_FORMAT_B8G8R8X8_UNORM:
  88657. info.isRGB = true;
  88658. info.isFourCC = false;
  88659. bpp = 32;
  88660. supported = true;
  88661. break;
  88662. }
  88663. if (supported) {
  88664. break;
  88665. }
  88666. default:
  88667. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  88668. return;
  88669. }
  88670. }
  88671. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  88672. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  88673. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  88674. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  88675. if (computeFormats) {
  88676. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  88677. }
  88678. mipmapCount = 1;
  88679. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  88680. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88681. }
  88682. for (var face = 0; face < faces; face++) {
  88683. width = header[off_width];
  88684. height = header[off_height];
  88685. for (mip = 0; mip < mipmapCount; ++mip) {
  88686. if (lodIndex === -1 || lodIndex === mip) {
  88687. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  88688. var i = (lodIndex === -1) ? mip : 0;
  88689. if (!info.isCompressed && info.isFourCC) {
  88690. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88691. dataLength = width * height * 4;
  88692. var floatArray = null;
  88693. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  88694. if (bpp === 128) {
  88695. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88696. if (sphericalPolynomialFaces && i == 0) {
  88697. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88698. }
  88699. }
  88700. else if (bpp === 64) {
  88701. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88702. if (sphericalPolynomialFaces && i == 0) {
  88703. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88704. }
  88705. }
  88706. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88707. }
  88708. else {
  88709. if (bpp === 128) {
  88710. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88711. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88712. if (sphericalPolynomialFaces && i == 0) {
  88713. sphericalPolynomialFaces.push(floatArray);
  88714. }
  88715. }
  88716. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  88717. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88718. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88719. if (sphericalPolynomialFaces && i == 0) {
  88720. sphericalPolynomialFaces.push(floatArray);
  88721. }
  88722. }
  88723. else { // 64
  88724. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88725. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  88726. if (sphericalPolynomialFaces && i == 0) {
  88727. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  88728. }
  88729. }
  88730. }
  88731. if (floatArray) {
  88732. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  88733. }
  88734. }
  88735. else if (info.isRGB) {
  88736. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88737. if (bpp === 24) {
  88738. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  88739. dataLength = width * height * 3;
  88740. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  88741. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88742. }
  88743. else { // 32
  88744. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88745. dataLength = width * height * 4;
  88746. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  88747. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88748. }
  88749. }
  88750. else if (info.isLuminance) {
  88751. var unpackAlignment = engine._getUnpackAlignement();
  88752. var unpaddedRowSize = width;
  88753. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  88754. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  88755. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  88756. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  88757. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88758. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  88759. }
  88760. else {
  88761. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  88762. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  88763. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88764. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  88765. }
  88766. }
  88767. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  88768. width *= 0.5;
  88769. height *= 0.5;
  88770. width = Math.max(1.0, width);
  88771. height = Math.max(1.0, height);
  88772. }
  88773. if (currentFace !== undefined) {
  88774. // Loading a single face
  88775. break;
  88776. }
  88777. }
  88778. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  88779. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  88780. size: header[off_width],
  88781. right: sphericalPolynomialFaces[0],
  88782. left: sphericalPolynomialFaces[1],
  88783. up: sphericalPolynomialFaces[2],
  88784. down: sphericalPolynomialFaces[3],
  88785. front: sphericalPolynomialFaces[4],
  88786. back: sphericalPolynomialFaces[5],
  88787. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  88788. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  88789. gammaSpace: false,
  88790. });
  88791. }
  88792. else {
  88793. info.sphericalPolynomial = undefined;
  88794. }
  88795. };
  88796. DDSTools.StoreLODInAlphaChannel = false;
  88797. return DDSTools;
  88798. }());
  88799. BABYLON.DDSTools = DDSTools;
  88800. })(BABYLON || (BABYLON = {}));
  88801. //# sourceMappingURL=babylon.dds.js.map
  88802. var BABYLON;
  88803. (function (BABYLON) {
  88804. /**
  88805. * Implementation of the DDS Texture Loader.
  88806. */
  88807. var DDSTextureLoader = /** @class */ (function () {
  88808. function DDSTextureLoader() {
  88809. /**
  88810. * Defines wether the loader supports cascade loading the different faces.
  88811. */
  88812. this.supportCascades = true;
  88813. }
  88814. /**
  88815. * This returns if the loader support the current file information.
  88816. * @param extension defines the file extension of the file being loaded
  88817. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88818. * @param fallback defines the fallback internal texture if any
  88819. * @param isBase64 defines whether the texture is encoded as a base64
  88820. * @param isBuffer defines whether the texture data are stored as a buffer
  88821. * @returns true if the loader can load the specified file
  88822. */
  88823. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88824. return extension.indexOf(".dds") === 0;
  88825. };
  88826. /**
  88827. * Transform the url before loading if required.
  88828. * @param rootUrl the url of the texture
  88829. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88830. * @returns the transformed texture
  88831. */
  88832. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88833. return rootUrl;
  88834. };
  88835. /**
  88836. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88837. * @param rootUrl the url of the texture
  88838. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88839. * @returns the fallback texture
  88840. */
  88841. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88842. return null;
  88843. };
  88844. /**
  88845. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88846. * @param data contains the texture data
  88847. * @param texture defines the BabylonJS internal texture
  88848. * @param createPolynomials will be true if polynomials have been requested
  88849. * @param onLoad defines the callback to trigger once the texture is ready
  88850. * @param onError defines the callback to trigger in case of error
  88851. */
  88852. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  88853. var engine = texture.getEngine();
  88854. var info;
  88855. var loadMipmap = false;
  88856. if (Array.isArray(imgs)) {
  88857. for (var index = 0; index < imgs.length; index++) {
  88858. var data_1 = imgs[index];
  88859. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  88860. texture.width = info.width;
  88861. texture.height = info.height;
  88862. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  88863. engine._unpackFlipY(info.isCompressed);
  88864. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  88865. if (!info.isFourCC && info.mipmapCount === 1) {
  88866. engine.generateMipMapsForCubemap(texture);
  88867. }
  88868. }
  88869. }
  88870. else {
  88871. var data = imgs;
  88872. info = BABYLON.DDSTools.GetDDSInfo(data);
  88873. texture.width = info.width;
  88874. texture.height = info.height;
  88875. if (createPolynomials) {
  88876. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  88877. }
  88878. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  88879. engine._unpackFlipY(info.isCompressed);
  88880. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  88881. if (!info.isFourCC && info.mipmapCount === 1) {
  88882. engine.generateMipMapsForCubemap(texture);
  88883. }
  88884. }
  88885. engine._setCubeMapTextureParams(loadMipmap);
  88886. texture.isReady = true;
  88887. if (onLoad) {
  88888. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  88889. }
  88890. };
  88891. /**
  88892. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88893. * @param data contains the texture data
  88894. * @param texture defines the BabylonJS internal texture
  88895. * @param callback defines the method to call once ready to upload
  88896. */
  88897. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  88898. var info = BABYLON.DDSTools.GetDDSInfo(data);
  88899. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  88900. callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {
  88901. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  88902. });
  88903. };
  88904. return DDSTextureLoader;
  88905. }());
  88906. // Register the loader.
  88907. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  88908. })(BABYLON || (BABYLON = {}));
  88909. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  88910. var BABYLON;
  88911. (function (BABYLON) {
  88912. /*
  88913. * Based on jsTGALoader - Javascript loader for TGA file
  88914. * By Vincent Thibault
  88915. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  88916. */
  88917. var TGATools = /** @class */ (function () {
  88918. function TGATools() {
  88919. }
  88920. TGATools.GetTGAHeader = function (data) {
  88921. var offset = 0;
  88922. var header = {
  88923. id_length: data[offset++],
  88924. colormap_type: data[offset++],
  88925. image_type: data[offset++],
  88926. colormap_index: data[offset++] | data[offset++] << 8,
  88927. colormap_length: data[offset++] | data[offset++] << 8,
  88928. colormap_size: data[offset++],
  88929. origin: [
  88930. data[offset++] | data[offset++] << 8,
  88931. data[offset++] | data[offset++] << 8
  88932. ],
  88933. width: data[offset++] | data[offset++] << 8,
  88934. height: data[offset++] | data[offset++] << 8,
  88935. pixel_size: data[offset++],
  88936. flags: data[offset++]
  88937. };
  88938. return header;
  88939. };
  88940. /**
  88941. * Uploads TGA content to a Babylon Texture
  88942. * @hidden
  88943. */
  88944. TGATools.UploadContent = function (texture, data) {
  88945. // Not enough data to contain header ?
  88946. if (data.length < 19) {
  88947. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  88948. return;
  88949. }
  88950. // Read Header
  88951. var offset = 18;
  88952. var header = TGATools.GetTGAHeader(data);
  88953. // Assume it's a valid Targa file.
  88954. if (header.id_length + offset > data.length) {
  88955. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  88956. return;
  88957. }
  88958. // Skip not needed data
  88959. offset += header.id_length;
  88960. var use_rle = false;
  88961. var use_pal = false;
  88962. var use_grey = false;
  88963. // Get some informations.
  88964. switch (header.image_type) {
  88965. case TGATools._TYPE_RLE_INDEXED:
  88966. use_rle = true;
  88967. case TGATools._TYPE_INDEXED:
  88968. use_pal = true;
  88969. break;
  88970. case TGATools._TYPE_RLE_RGB:
  88971. use_rle = true;
  88972. case TGATools._TYPE_RGB:
  88973. // use_rgb = true;
  88974. break;
  88975. case TGATools._TYPE_RLE_GREY:
  88976. use_rle = true;
  88977. case TGATools._TYPE_GREY:
  88978. use_grey = true;
  88979. break;
  88980. }
  88981. var pixel_data;
  88982. // var numAlphaBits = header.flags & 0xf;
  88983. var pixel_size = header.pixel_size >> 3;
  88984. var pixel_total = header.width * header.height * pixel_size;
  88985. // Read palettes
  88986. var palettes;
  88987. if (use_pal) {
  88988. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  88989. }
  88990. // Read LRE
  88991. if (use_rle) {
  88992. pixel_data = new Uint8Array(pixel_total);
  88993. var c, count, i;
  88994. var localOffset = 0;
  88995. var pixels = new Uint8Array(pixel_size);
  88996. while (offset < pixel_total && localOffset < pixel_total) {
  88997. c = data[offset++];
  88998. count = (c & 0x7f) + 1;
  88999. // RLE pixels
  89000. if (c & 0x80) {
  89001. // Bind pixel tmp array
  89002. for (i = 0; i < pixel_size; ++i) {
  89003. pixels[i] = data[offset++];
  89004. }
  89005. // Copy pixel array
  89006. for (i = 0; i < count; ++i) {
  89007. pixel_data.set(pixels, localOffset + i * pixel_size);
  89008. }
  89009. localOffset += pixel_size * count;
  89010. }
  89011. // Raw pixels
  89012. else {
  89013. count *= pixel_size;
  89014. for (i = 0; i < count; ++i) {
  89015. pixel_data[localOffset + i] = data[offset++];
  89016. }
  89017. localOffset += count;
  89018. }
  89019. }
  89020. }
  89021. // RAW Pixels
  89022. else {
  89023. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  89024. }
  89025. // Load to texture
  89026. var x_start, y_start, x_step, y_step, y_end, x_end;
  89027. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  89028. default:
  89029. case TGATools._ORIGIN_UL:
  89030. x_start = 0;
  89031. x_step = 1;
  89032. x_end = header.width;
  89033. y_start = 0;
  89034. y_step = 1;
  89035. y_end = header.height;
  89036. break;
  89037. case TGATools._ORIGIN_BL:
  89038. x_start = 0;
  89039. x_step = 1;
  89040. x_end = header.width;
  89041. y_start = header.height - 1;
  89042. y_step = -1;
  89043. y_end = -1;
  89044. break;
  89045. case TGATools._ORIGIN_UR:
  89046. x_start = header.width - 1;
  89047. x_step = -1;
  89048. x_end = -1;
  89049. y_start = 0;
  89050. y_step = 1;
  89051. y_end = header.height;
  89052. break;
  89053. case TGATools._ORIGIN_BR:
  89054. x_start = header.width - 1;
  89055. x_step = -1;
  89056. x_end = -1;
  89057. y_start = header.height - 1;
  89058. y_step = -1;
  89059. y_end = -1;
  89060. break;
  89061. }
  89062. // Load the specify method
  89063. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  89064. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  89065. var engine = texture.getEngine();
  89066. engine._uploadDataToTextureDirectly(texture, imageData);
  89067. };
  89068. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89069. var image = pixel_data, colormap = palettes;
  89070. var width = header.width, height = header.height;
  89071. var color, i = 0, x, y;
  89072. var imageData = new Uint8Array(width * height * 4);
  89073. for (y = y_start; y !== y_end; y += y_step) {
  89074. for (x = x_start; x !== x_end; x += x_step, i++) {
  89075. color = image[i];
  89076. imageData[(x + width * y) * 4 + 3] = 255;
  89077. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  89078. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  89079. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  89080. }
  89081. }
  89082. return imageData;
  89083. };
  89084. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89085. var image = pixel_data;
  89086. var width = header.width, height = header.height;
  89087. var color, i = 0, x, y;
  89088. var imageData = new Uint8Array(width * height * 4);
  89089. for (y = y_start; y !== y_end; y += y_step) {
  89090. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  89091. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  89092. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  89093. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  89094. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  89095. imageData[(x + width * y) * 4 + 0] = r;
  89096. imageData[(x + width * y) * 4 + 1] = g;
  89097. imageData[(x + width * y) * 4 + 2] = b;
  89098. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  89099. }
  89100. }
  89101. return imageData;
  89102. };
  89103. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89104. var image = pixel_data;
  89105. var width = header.width, height = header.height;
  89106. var i = 0, x, y;
  89107. var imageData = new Uint8Array(width * height * 4);
  89108. for (y = y_start; y !== y_end; y += y_step) {
  89109. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  89110. imageData[(x + width * y) * 4 + 3] = 255;
  89111. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89112. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89113. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89114. }
  89115. }
  89116. return imageData;
  89117. };
  89118. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89119. var image = pixel_data;
  89120. var width = header.width, height = header.height;
  89121. var i = 0, x, y;
  89122. var imageData = new Uint8Array(width * height * 4);
  89123. for (y = y_start; y !== y_end; y += y_step) {
  89124. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  89125. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89126. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89127. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89128. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  89129. }
  89130. }
  89131. return imageData;
  89132. };
  89133. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89134. var image = pixel_data;
  89135. var width = header.width, height = header.height;
  89136. var color, i = 0, x, y;
  89137. var imageData = new Uint8Array(width * height * 4);
  89138. for (y = y_start; y !== y_end; y += y_step) {
  89139. for (x = x_start; x !== x_end; x += x_step, i++) {
  89140. color = image[i];
  89141. imageData[(x + width * y) * 4 + 0] = color;
  89142. imageData[(x + width * y) * 4 + 1] = color;
  89143. imageData[(x + width * y) * 4 + 2] = color;
  89144. imageData[(x + width * y) * 4 + 3] = 255;
  89145. }
  89146. }
  89147. return imageData;
  89148. };
  89149. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89150. var image = pixel_data;
  89151. var width = header.width, height = header.height;
  89152. var i = 0, x, y;
  89153. var imageData = new Uint8Array(width * height * 4);
  89154. for (y = y_start; y !== y_end; y += y_step) {
  89155. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  89156. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  89157. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  89158. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89159. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  89160. }
  89161. }
  89162. return imageData;
  89163. };
  89164. //private static _TYPE_NO_DATA = 0;
  89165. TGATools._TYPE_INDEXED = 1;
  89166. TGATools._TYPE_RGB = 2;
  89167. TGATools._TYPE_GREY = 3;
  89168. TGATools._TYPE_RLE_INDEXED = 9;
  89169. TGATools._TYPE_RLE_RGB = 10;
  89170. TGATools._TYPE_RLE_GREY = 11;
  89171. TGATools._ORIGIN_MASK = 0x30;
  89172. TGATools._ORIGIN_SHIFT = 0x04;
  89173. TGATools._ORIGIN_BL = 0x00;
  89174. TGATools._ORIGIN_BR = 0x01;
  89175. TGATools._ORIGIN_UL = 0x02;
  89176. TGATools._ORIGIN_UR = 0x03;
  89177. return TGATools;
  89178. }());
  89179. BABYLON.TGATools = TGATools;
  89180. })(BABYLON || (BABYLON = {}));
  89181. //# sourceMappingURL=babylon.tga.js.map
  89182. var BABYLON;
  89183. (function (BABYLON) {
  89184. /**
  89185. * Implementation of the TGA Texture Loader.
  89186. */
  89187. var TGATextureLoader = /** @class */ (function () {
  89188. function TGATextureLoader() {
  89189. /**
  89190. * Defines wether the loader supports cascade loading the different faces.
  89191. */
  89192. this.supportCascades = false;
  89193. }
  89194. /**
  89195. * This returns if the loader support the current file information.
  89196. * @param extension defines the file extension of the file being loaded
  89197. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89198. * @param fallback defines the fallback internal texture if any
  89199. * @param isBase64 defines whether the texture is encoded as a base64
  89200. * @param isBuffer defines whether the texture data are stored as a buffer
  89201. * @returns true if the loader can load the specified file
  89202. */
  89203. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89204. return extension.indexOf(".tga") === 0;
  89205. };
  89206. /**
  89207. * Transform the url before loading if required.
  89208. * @param rootUrl the url of the texture
  89209. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89210. * @returns the transformed texture
  89211. */
  89212. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89213. return rootUrl;
  89214. };
  89215. /**
  89216. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89217. * @param rootUrl the url of the texture
  89218. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89219. * @returns the fallback texture
  89220. */
  89221. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89222. return null;
  89223. };
  89224. /**
  89225. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89226. * @param data contains the texture data
  89227. * @param texture defines the BabylonJS internal texture
  89228. * @param createPolynomials will be true if polynomials have been requested
  89229. * @param onLoad defines the callback to trigger once the texture is ready
  89230. * @param onError defines the callback to trigger in case of error
  89231. */
  89232. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89233. throw ".env not supported in Cube.";
  89234. };
  89235. /**
  89236. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89237. * @param data contains the texture data
  89238. * @param texture defines the BabylonJS internal texture
  89239. * @param callback defines the method to call once ready to upload
  89240. */
  89241. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  89242. var uintData = new Uint8Array(data);
  89243. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  89244. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  89245. BABYLON.TGATools.UploadContent(texture, uintData);
  89246. });
  89247. };
  89248. return TGATextureLoader;
  89249. }());
  89250. // Register the loader.
  89251. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  89252. })(BABYLON || (BABYLON = {}));
  89253. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  89254. var BABYLON;
  89255. (function (BABYLON) {
  89256. /**
  89257. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  89258. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  89259. */
  89260. var KhronosTextureContainer = /** @class */ (function () {
  89261. /**
  89262. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  89263. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  89264. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  89265. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  89266. */
  89267. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  89268. this.arrayBuffer = arrayBuffer;
  89269. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  89270. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  89271. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  89272. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  89273. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  89274. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  89275. BABYLON.Tools.Error("texture missing KTX identifier");
  89276. return;
  89277. }
  89278. // load the reset of the header in native 32 bit int
  89279. var header = new Int32Array(this.arrayBuffer, 12, 13);
  89280. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  89281. var oppositeEndianess = header[0] === 0x01020304;
  89282. // read all the header elements in order they exist in the file, without modification (sans endainness)
  89283. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  89284. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  89285. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  89286. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  89287. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  89288. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  89289. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  89290. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  89291. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  89292. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  89293. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  89294. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  89295. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  89296. if (this.glType !== 0) {
  89297. BABYLON.Tools.Error("only compressed formats currently supported");
  89298. return;
  89299. }
  89300. else {
  89301. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  89302. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  89303. }
  89304. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  89305. BABYLON.Tools.Error("only 2D textures currently supported");
  89306. return;
  89307. }
  89308. if (this.numberOfArrayElements !== 0) {
  89309. BABYLON.Tools.Error("texture arrays not currently supported");
  89310. return;
  89311. }
  89312. if (this.numberOfFaces !== facesExpected) {
  89313. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  89314. return;
  89315. }
  89316. // we now have a completely validated file, so could use existence of loadType as success
  89317. // would need to make this more elaborate & adjust checks above to support more than one load type
  89318. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  89319. }
  89320. // not as fast hardware based, but will probably never need to use
  89321. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  89322. return ((val & 0xFF) << 24)
  89323. | ((val & 0xFF00) << 8)
  89324. | ((val >> 8) & 0xFF00)
  89325. | ((val >> 24) & 0xFF);
  89326. };
  89327. /**
  89328. * Uploads KTX content to a Babylon Texture.
  89329. * It is assumed that the texture has already been created & is currently bound
  89330. * @hidden
  89331. */
  89332. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  89333. switch (this.loadType) {
  89334. case KhronosTextureContainer.COMPRESSED_2D:
  89335. this._upload2DCompressedLevels(texture, loadMipmaps);
  89336. break;
  89337. case KhronosTextureContainer.TEX_2D:
  89338. case KhronosTextureContainer.COMPRESSED_3D:
  89339. case KhronosTextureContainer.TEX_3D:
  89340. }
  89341. };
  89342. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  89343. // initialize width & height for level 1
  89344. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  89345. var width = this.pixelWidth;
  89346. var height = this.pixelHeight;
  89347. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  89348. for (var level = 0; level < mipmapCount; level++) {
  89349. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  89350. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  89351. for (var face = 0; face < this.numberOfFaces; face++) {
  89352. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  89353. var engine = texture.getEngine();
  89354. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  89355. dataOffset += imageSize; // add size of the image for the next face/mipmap
  89356. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  89357. }
  89358. width = Math.max(1.0, width * 0.5);
  89359. height = Math.max(1.0, height * 0.5);
  89360. }
  89361. };
  89362. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  89363. // load types
  89364. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  89365. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  89366. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  89367. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  89368. return KhronosTextureContainer;
  89369. }());
  89370. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  89371. })(BABYLON || (BABYLON = {}));
  89372. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  89373. var BABYLON;
  89374. (function (BABYLON) {
  89375. /**
  89376. * Implementation of the KTX Texture Loader.
  89377. */
  89378. var KTXTextureLoader = /** @class */ (function () {
  89379. function KTXTextureLoader() {
  89380. /**
  89381. * Defines wether the loader supports cascade loading the different faces.
  89382. */
  89383. this.supportCascades = false;
  89384. }
  89385. /**
  89386. * This returns if the loader support the current file information.
  89387. * @param extension defines the file extension of the file being loaded
  89388. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89389. * @param fallback defines the fallback internal texture if any
  89390. * @param isBase64 defines whether the texture is encoded as a base64
  89391. * @param isBuffer defines whether the texture data are stored as a buffer
  89392. * @returns true if the loader can load the specified file
  89393. */
  89394. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89395. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  89396. return true;
  89397. }
  89398. return false;
  89399. };
  89400. /**
  89401. * Transform the url before loading if required.
  89402. * @param rootUrl the url of the texture
  89403. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89404. * @returns the transformed texture
  89405. */
  89406. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89407. var lastDot = rootUrl.lastIndexOf('.');
  89408. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  89409. };
  89410. /**
  89411. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89412. * @param rootUrl the url of the texture
  89413. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89414. * @returns the fallback texture
  89415. */
  89416. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89417. // remove the format appended to the rootUrl in the original createCubeTexture call.
  89418. var exp = new RegExp("" + textureFormatInUse + "$");
  89419. return rootUrl.replace(exp, "");
  89420. };
  89421. /**
  89422. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89423. * @param data contains the texture data
  89424. * @param texture defines the BabylonJS internal texture
  89425. * @param createPolynomials will be true if polynomials have been requested
  89426. * @param onLoad defines the callback to trigger once the texture is ready
  89427. * @param onError defines the callback to trigger in case of error
  89428. */
  89429. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89430. if (Array.isArray(data)) {
  89431. return;
  89432. }
  89433. var engine = texture.getEngine();
  89434. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  89435. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  89436. engine._unpackFlipY(true);
  89437. ktx.uploadLevels(texture, texture.generateMipMaps);
  89438. texture.width = ktx.pixelWidth;
  89439. texture.height = ktx.pixelHeight;
  89440. engine._setCubeMapTextureParams(loadMipmap);
  89441. texture.isReady = true;
  89442. };
  89443. /**
  89444. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89445. * @param data contains the texture data
  89446. * @param texture defines the BabylonJS internal texture
  89447. * @param callback defines the method to call once ready to upload
  89448. */
  89449. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  89450. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  89451. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  89452. ktx.uploadLevels(texture, texture.generateMipMaps);
  89453. });
  89454. };
  89455. return KTXTextureLoader;
  89456. }());
  89457. // Register the loader.
  89458. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  89459. })(BABYLON || (BABYLON = {}));
  89460. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  89461. var BABYLON;
  89462. (function (BABYLON) {
  89463. /**
  89464. * Sets of helpers addressing the serialization and deserialization of environment texture
  89465. * stored in a BabylonJS env file.
  89466. * Those files are usually stored as .env files.
  89467. */
  89468. var EnvironmentTextureTools = /** @class */ (function () {
  89469. function EnvironmentTextureTools() {
  89470. }
  89471. /**
  89472. * Gets the environment info from an env file.
  89473. * @param data The array buffer containing the .env bytes.
  89474. * @returns the environment file info (the json header) if successfully parsed.
  89475. */
  89476. EnvironmentTextureTools.GetEnvInfo = function (data) {
  89477. var dataView = new DataView(data);
  89478. var pos = 0;
  89479. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  89480. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  89481. BABYLON.Tools.Error('Not a babylon environment map');
  89482. return null;
  89483. }
  89484. }
  89485. // Read json manifest - collect characters up to null terminator
  89486. var manifestString = '';
  89487. var charCode = 0x00;
  89488. while ((charCode = dataView.getUint8(pos++))) {
  89489. manifestString += String.fromCharCode(charCode);
  89490. }
  89491. var manifest = JSON.parse(manifestString);
  89492. if (manifest.specular) {
  89493. // Extend the header with the position of the payload.
  89494. manifest.specular.specularDataPosition = pos;
  89495. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  89496. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  89497. }
  89498. return manifest;
  89499. };
  89500. /**
  89501. * Creates an environment texture from a loaded cube texture.
  89502. * @param texture defines the cube texture to convert in env file
  89503. * @return a promise containing the environment data if succesfull.
  89504. */
  89505. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  89506. var _this = this;
  89507. var internalTexture = texture.getInternalTexture();
  89508. if (!internalTexture) {
  89509. return Promise.reject("The cube texture is invalid.");
  89510. }
  89511. if (!texture._prefiltered) {
  89512. return Promise.reject("The cube texture is invalid (not prefiltered).");
  89513. }
  89514. var engine = internalTexture.getEngine();
  89515. if (engine && engine.premultipliedAlpha) {
  89516. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  89517. }
  89518. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  89519. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  89520. }
  89521. var canvas = engine.getRenderingCanvas();
  89522. if (!canvas) {
  89523. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  89524. }
  89525. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89526. if (!engine.getCaps().textureFloatRender) {
  89527. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89528. if (!engine.getCaps().textureHalfFloatRender) {
  89529. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  89530. }
  89531. }
  89532. var cubeWidth = internalTexture.width;
  89533. var hostingScene = new BABYLON.Scene(engine);
  89534. var specularTextures = {};
  89535. var promises = [];
  89536. // Read and collect all mipmaps data from the cube.
  89537. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  89538. mipmapsCount = Math.round(mipmapsCount);
  89539. var _loop_1 = function (i) {
  89540. var faceWidth = Math.pow(2, mipmapsCount - i);
  89541. var _loop_2 = function (face) {
  89542. var data = texture.readPixels(face, i);
  89543. // Creates a temp texture with the face data.
  89544. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  89545. // And rgbdEncode them.
  89546. var promise = new Promise(function (resolve, reject) {
  89547. 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);
  89548. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  89549. rgbdPostProcess.onApply = function (effect) {
  89550. effect._bindTexture("textureSampler", tempTexture);
  89551. };
  89552. // As the process needs to happen on the main canvas, keep track of the current size
  89553. var currentW = engine.getRenderWidth();
  89554. var currentH = engine.getRenderHeight();
  89555. // Set the desired size for the texture
  89556. engine.setSize(faceWidth, faceWidth);
  89557. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  89558. // Reading datas from WebGL
  89559. BABYLON.Tools.ToBlob(canvas, function (blob) {
  89560. var fileReader = new FileReader();
  89561. fileReader.onload = function (event) {
  89562. var arrayBuffer = event.target.result;
  89563. specularTextures[i * 6 + face] = arrayBuffer;
  89564. resolve();
  89565. };
  89566. fileReader.readAsArrayBuffer(blob);
  89567. });
  89568. // Reapply the previous canvas size
  89569. engine.setSize(currentW, currentH);
  89570. });
  89571. });
  89572. promises.push(promise);
  89573. };
  89574. // All faces of the cube.
  89575. for (var face = 0; face < 6; face++) {
  89576. _loop_2(face);
  89577. }
  89578. };
  89579. for (var i = 0; i <= mipmapsCount; i++) {
  89580. _loop_1(i);
  89581. }
  89582. // Once all the textures haves been collected as RGBD stored in PNGs
  89583. return Promise.all(promises).then(function () {
  89584. // We can delete the hosting scene keeping track of all the creation objects
  89585. hostingScene.dispose();
  89586. // Creates the json header for the env texture
  89587. var info = {
  89588. version: 1,
  89589. width: cubeWidth,
  89590. irradiance: _this._CreateEnvTextureIrradiance(texture),
  89591. specular: {
  89592. mipmaps: [],
  89593. lodGenerationScale: texture.lodGenerationScale
  89594. }
  89595. };
  89596. // Sets the specular image data information
  89597. var position = 0;
  89598. for (var i = 0; i <= mipmapsCount; i++) {
  89599. for (var face = 0; face < 6; face++) {
  89600. var byteLength = specularTextures[i * 6 + face].byteLength;
  89601. info.specular.mipmaps.push({
  89602. length: byteLength,
  89603. position: position
  89604. });
  89605. position += byteLength;
  89606. }
  89607. }
  89608. // Encode the JSON as an array buffer
  89609. var infoString = JSON.stringify(info);
  89610. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  89611. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  89612. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  89613. infoView[i] = infoString.charCodeAt(i);
  89614. }
  89615. // Ends up with a null terminator for easier parsing
  89616. infoView[infoString.length] = 0x00;
  89617. // Computes the final required size and creates the storage
  89618. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  89619. var finalBuffer = new ArrayBuffer(totalSize);
  89620. var finalBufferView = new Uint8Array(finalBuffer);
  89621. var dataView = new DataView(finalBuffer);
  89622. // Copy the magic bytes identifying the file in
  89623. var pos = 0;
  89624. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  89625. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  89626. }
  89627. // Add the json info
  89628. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  89629. pos += infoBuffer.byteLength;
  89630. // Finally inserts the texture data
  89631. for (var i = 0; i <= mipmapsCount; i++) {
  89632. for (var face = 0; face < 6; face++) {
  89633. var dataBuffer = specularTextures[i * 6 + face];
  89634. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  89635. pos += dataBuffer.byteLength;
  89636. }
  89637. }
  89638. // Voila
  89639. return finalBuffer;
  89640. });
  89641. };
  89642. /**
  89643. * Creates a JSON representation of the spherical data.
  89644. * @param texture defines the texture containing the polynomials
  89645. * @return the JSON representation of the spherical info
  89646. */
  89647. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  89648. var polynmials = texture.sphericalPolynomial;
  89649. if (polynmials == null) {
  89650. return null;
  89651. }
  89652. return {
  89653. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  89654. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  89655. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  89656. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  89657. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  89658. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  89659. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  89660. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  89661. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  89662. };
  89663. };
  89664. /**
  89665. * Uploads the texture info contained in the env file to the GPU.
  89666. * @param texture defines the internal texture to upload to
  89667. * @param arrayBuffer defines the buffer cotaining the data to load
  89668. * @param info defines the texture info retrieved through the GetEnvInfo method
  89669. * @returns a promise
  89670. */
  89671. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  89672. if (info.version !== 1) {
  89673. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  89674. }
  89675. var specularInfo = info.specular;
  89676. if (!specularInfo) {
  89677. // Nothing else parsed so far
  89678. return Promise.resolve();
  89679. }
  89680. // Double checks the enclosed info
  89681. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  89682. mipmapsCount = Math.round(mipmapsCount) + 1;
  89683. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  89684. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  89685. }
  89686. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  89687. var imageData = new Array(mipmapsCount);
  89688. for (var i = 0; i < mipmapsCount; i++) {
  89689. imageData[i] = new Array(6);
  89690. for (var face = 0; face < 6; face++) {
  89691. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  89692. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  89693. }
  89694. }
  89695. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  89696. };
  89697. /**
  89698. * Uploads the levels of image data to the GPU.
  89699. * @param texture defines the internal texture to upload to
  89700. * @param imageData defines the array buffer views of image data [mipmap][face]
  89701. * @returns a promise
  89702. */
  89703. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  89704. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  89705. throw new Error("Texture size must be a power of two");
  89706. }
  89707. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  89708. // Gets everything ready.
  89709. var engine = texture.getEngine();
  89710. var expandTexture = false;
  89711. var generateNonLODTextures = false;
  89712. var rgbdPostProcess = null;
  89713. var cubeRtt = null;
  89714. var lodTextures = null;
  89715. var caps = engine.getCaps();
  89716. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89717. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89718. texture.generateMipMaps = true;
  89719. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  89720. // Add extra process if texture lod is not supported
  89721. if (!caps.textureLOD) {
  89722. expandTexture = false;
  89723. generateNonLODTextures = true;
  89724. lodTextures = {};
  89725. }
  89726. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  89727. else if (engine.webGLVersion < 2) {
  89728. expandTexture = false;
  89729. }
  89730. // If half float available we can uncompress the texture
  89731. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  89732. expandTexture = true;
  89733. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89734. }
  89735. // If full float available we can uncompress the texture
  89736. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  89737. expandTexture = true;
  89738. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89739. }
  89740. // Expand the texture if possible
  89741. if (expandTexture) {
  89742. // Simply run through the decode PP
  89743. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  89744. texture._isRGBD = false;
  89745. texture.invertY = false;
  89746. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  89747. generateDepthBuffer: false,
  89748. generateMipMaps: true,
  89749. generateStencilBuffer: false,
  89750. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  89751. type: texture.type,
  89752. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  89753. });
  89754. }
  89755. else {
  89756. texture._isRGBD = true;
  89757. texture.invertY = true;
  89758. // In case of missing support, applies the same patch than DDS files.
  89759. if (generateNonLODTextures) {
  89760. var mipSlices = 3;
  89761. var scale = texture._lodGenerationScale;
  89762. var offset = texture._lodGenerationOffset;
  89763. for (var i = 0; i < mipSlices; i++) {
  89764. //compute LOD from even spacing in smoothness (matching shader calculation)
  89765. var smoothness = i / (mipSlices - 1);
  89766. var roughness = 1 - smoothness;
  89767. var minLODIndex = offset; // roughness = 0
  89768. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  89769. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  89770. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  89771. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  89772. glTextureFromLod.isCube = true;
  89773. glTextureFromLod.invertY = true;
  89774. glTextureFromLod.generateMipMaps = false;
  89775. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  89776. // Wrap in a base texture for easy binding.
  89777. var lodTexture = new BABYLON.BaseTexture(null);
  89778. lodTexture.isCube = true;
  89779. lodTexture._texture = glTextureFromLod;
  89780. lodTextures[mipmapIndex] = lodTexture;
  89781. switch (i) {
  89782. case 0:
  89783. texture._lodTextureLow = lodTexture;
  89784. break;
  89785. case 1:
  89786. texture._lodTextureMid = lodTexture;
  89787. break;
  89788. case 2:
  89789. texture._lodTextureHigh = lodTexture;
  89790. break;
  89791. }
  89792. }
  89793. }
  89794. }
  89795. var promises = [];
  89796. var _loop_3 = function (i) {
  89797. var _loop_4 = function (face) {
  89798. // Constructs an image element from image data
  89799. var bytes = imageData[i][face];
  89800. var blob = new Blob([bytes], { type: 'image/png' });
  89801. var url = URL.createObjectURL(blob);
  89802. var image = new Image();
  89803. image.src = url;
  89804. // Enqueue promise to upload to the texture.
  89805. var promise = new Promise(function (resolve, reject) {
  89806. image.onload = function () {
  89807. if (expandTexture) {
  89808. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  89809. reject(message);
  89810. }, image);
  89811. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  89812. // Uncompress the data to a RTT
  89813. rgbdPostProcess.onApply = function (effect) {
  89814. effect._bindTexture("textureSampler", tempTexture_1);
  89815. effect.setFloat2("scale", 1, 1);
  89816. };
  89817. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  89818. // Cleanup
  89819. engine.restoreDefaultFramebuffer();
  89820. tempTexture_1.dispose();
  89821. window.URL.revokeObjectURL(url);
  89822. resolve();
  89823. });
  89824. }
  89825. else {
  89826. engine._uploadImageToTexture(texture, image, face, i);
  89827. // Upload the face to the non lod texture support
  89828. if (generateNonLODTextures) {
  89829. var lodTexture = lodTextures[i];
  89830. if (lodTexture) {
  89831. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  89832. }
  89833. }
  89834. resolve();
  89835. }
  89836. };
  89837. image.onerror = function (error) {
  89838. reject(error);
  89839. };
  89840. });
  89841. promises.push(promise);
  89842. };
  89843. // All faces
  89844. for (var face = 0; face < 6; face++) {
  89845. _loop_4(face);
  89846. }
  89847. };
  89848. // All mipmaps up to provided number of images
  89849. for (var i = 0; i < imageData.length; i++) {
  89850. _loop_3(i);
  89851. }
  89852. // Fill remaining mipmaps with black textures.
  89853. if (imageData.length < mipmapsCount) {
  89854. var data = void 0;
  89855. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  89856. var dataLength = size * size * 4;
  89857. switch (texture.type) {
  89858. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  89859. data = new Uint8Array(dataLength);
  89860. break;
  89861. }
  89862. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  89863. data = new Uint16Array(dataLength);
  89864. break;
  89865. }
  89866. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  89867. data = new Float32Array(dataLength);
  89868. break;
  89869. }
  89870. }
  89871. for (var i = imageData.length; i < mipmapsCount; i++) {
  89872. for (var face = 0; face < 6; face++) {
  89873. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  89874. }
  89875. }
  89876. }
  89877. // Once all done, finishes the cleanup and return
  89878. return Promise.all(promises).then(function () {
  89879. // Release temp RTT.
  89880. if (cubeRtt) {
  89881. engine._releaseFramebufferObjects(cubeRtt);
  89882. cubeRtt._swapAndDie(texture);
  89883. }
  89884. // Release temp Post Process.
  89885. if (rgbdPostProcess) {
  89886. rgbdPostProcess.dispose();
  89887. }
  89888. // Flag internal texture as ready in case they are in use.
  89889. if (generateNonLODTextures) {
  89890. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  89891. texture._lodTextureHigh._texture.isReady = true;
  89892. }
  89893. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  89894. texture._lodTextureMid._texture.isReady = true;
  89895. }
  89896. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  89897. texture._lodTextureLow._texture.isReady = true;
  89898. }
  89899. }
  89900. });
  89901. };
  89902. /**
  89903. * Uploads spherical polynomials information to the texture.
  89904. * @param texture defines the texture we are trying to upload the information to
  89905. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  89906. */
  89907. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  89908. if (info.version !== 1) {
  89909. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  89910. }
  89911. var irradianceInfo = info.irradiance;
  89912. if (!irradianceInfo) {
  89913. return;
  89914. }
  89915. var sp = new BABYLON.SphericalPolynomial();
  89916. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  89917. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  89918. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  89919. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  89920. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  89921. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  89922. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  89923. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  89924. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  89925. texture._sphericalPolynomial = sp;
  89926. };
  89927. /**
  89928. * Magic number identifying the env file.
  89929. */
  89930. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  89931. return EnvironmentTextureTools;
  89932. }());
  89933. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  89934. })(BABYLON || (BABYLON = {}));
  89935. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  89936. var BABYLON;
  89937. (function (BABYLON) {
  89938. /**
  89939. * Implementation of the ENV Texture Loader.
  89940. */
  89941. var ENVTextureLoader = /** @class */ (function () {
  89942. function ENVTextureLoader() {
  89943. /**
  89944. * Defines wether the loader supports cascade loading the different faces.
  89945. */
  89946. this.supportCascades = false;
  89947. }
  89948. /**
  89949. * This returns if the loader support the current file information.
  89950. * @param extension defines the file extension of the file being loaded
  89951. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89952. * @param fallback defines the fallback internal texture if any
  89953. * @param isBase64 defines whether the texture is encoded as a base64
  89954. * @param isBuffer defines whether the texture data are stored as a buffer
  89955. * @returns true if the loader can load the specified file
  89956. */
  89957. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89958. return extension.indexOf(".env") === 0;
  89959. };
  89960. /**
  89961. * Transform the url before loading if required.
  89962. * @param rootUrl the url of the texture
  89963. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89964. * @returns the transformed texture
  89965. */
  89966. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89967. return rootUrl;
  89968. };
  89969. /**
  89970. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89971. * @param rootUrl the url of the texture
  89972. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89973. * @returns the fallback texture
  89974. */
  89975. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89976. return null;
  89977. };
  89978. /**
  89979. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89980. * @param data contains the texture data
  89981. * @param texture defines the BabylonJS internal texture
  89982. * @param createPolynomials will be true if polynomials have been requested
  89983. * @param onLoad defines the callback to trigger once the texture is ready
  89984. * @param onError defines the callback to trigger in case of error
  89985. */
  89986. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89987. if (Array.isArray(data)) {
  89988. return;
  89989. }
  89990. data = data;
  89991. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  89992. if (info) {
  89993. texture.width = info.width;
  89994. texture.height = info.width;
  89995. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  89996. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  89997. texture.isReady = true;
  89998. if (onLoad) {
  89999. onLoad();
  90000. }
  90001. });
  90002. }
  90003. else if (onError) {
  90004. onError("Can not parse the environment file", null);
  90005. }
  90006. };
  90007. /**
  90008. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90009. * @param data contains the texture data
  90010. * @param texture defines the BabylonJS internal texture
  90011. * @param callback defines the method to call once ready to upload
  90012. */
  90013. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  90014. throw ".env not supported in 2d.";
  90015. };
  90016. return ENVTextureLoader;
  90017. }());
  90018. // Register the loader.
  90019. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  90020. })(BABYLON || (BABYLON = {}));
  90021. //# sourceMappingURL=babylon.envTextureLoader.js.map
  90022. var BABYLON;
  90023. (function (BABYLON) {
  90024. /**
  90025. * Renders a layer on top of an existing scene
  90026. */
  90027. var UtilityLayerRenderer = /** @class */ (function () {
  90028. /**
  90029. * Instantiates a UtilityLayerRenderer
  90030. * @param originalScene the original scene that will be rendered on top of
  90031. */
  90032. function UtilityLayerRenderer(
  90033. /** the original scene that will be rendered on top of */
  90034. originalScene) {
  90035. var _this = this;
  90036. this.originalScene = originalScene;
  90037. this._pointerCaptures = {};
  90038. this._lastPointerEvents = {};
  90039. /**
  90040. * If the utility layer should automatically be rendered on top of existing scene
  90041. */
  90042. this.shouldRender = true;
  90043. /**
  90044. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  90045. */
  90046. this.onlyCheckPointerDownEvents = true;
  90047. /**
  90048. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  90049. */
  90050. this.processAllEvents = false;
  90051. /**
  90052. * Observable raised when the pointer move from the utility layer scene to the main scene
  90053. */
  90054. this.onPointerOutObservable = new BABYLON.Observable();
  90055. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  90056. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  90057. this.utilityLayerScene._allowPostProcessClear = false;
  90058. originalScene.getEngine().scenes.pop();
  90059. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  90060. this.utilityLayerScene.detachControl();
  90061. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  90062. if (!_this.processAllEvents) {
  90063. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  90064. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  90065. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  90066. return;
  90067. }
  90068. }
  90069. var pointerEvent = (prePointerInfo.event);
  90070. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  90071. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90072. return;
  90073. }
  90074. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  90075. if (!prePointerInfo.ray && utilityScenePick) {
  90076. prePointerInfo.ray = utilityScenePick.ray;
  90077. }
  90078. // always fire the prepointer oversvable
  90079. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  90080. // allow every non pointer down event to flow to the utility layer
  90081. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  90082. if (!prePointerInfo.skipOnPointerObservable) {
  90083. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90084. }
  90085. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  90086. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90087. }
  90088. return;
  90089. }
  90090. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  90091. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  90092. if (utilityScenePick && utilityScenePick.hit) {
  90093. if (!prePointerInfo.skipOnPointerObservable) {
  90094. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90095. }
  90096. prePointerInfo.skipOnPointerObservable = true;
  90097. }
  90098. }
  90099. else {
  90100. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  90101. var pointerEvent_1 = (prePointerInfo.event);
  90102. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  90103. if (originalScenePick && utilityScenePick) {
  90104. // No pick in utility scene
  90105. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  90106. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90107. // We touched an utility mesh present in the main scene
  90108. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90109. prePointerInfo.skipOnPointerObservable = true;
  90110. }
  90111. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  90112. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  90113. }
  90114. }
  90115. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  90116. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  90117. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  90118. // If a previous utility layer set this, do not unset this
  90119. if (!prePointerInfo.skipOnPointerObservable) {
  90120. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  90121. }
  90122. }
  90123. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  90124. // We have a pick in both scenes but main is closer than utility
  90125. // We touched an utility mesh present in the main scene
  90126. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90127. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90128. prePointerInfo.skipOnPointerObservable = true;
  90129. }
  90130. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  90131. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  90132. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  90133. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  90134. }
  90135. }
  90136. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  90137. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  90138. }
  90139. }
  90140. }
  90141. });
  90142. // Render directly on top of existing scene without clearing
  90143. this.utilityLayerScene.autoClear = false;
  90144. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  90145. if (_this.shouldRender) {
  90146. _this.render();
  90147. }
  90148. });
  90149. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  90150. _this.dispose();
  90151. });
  90152. this._updateCamera();
  90153. }
  90154. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  90155. /**
  90156. * 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)
  90157. */
  90158. get: function () {
  90159. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  90160. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  90161. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  90162. UtilityLayerRenderer._DefaultUtilityLayer = null;
  90163. });
  90164. }
  90165. return UtilityLayerRenderer._DefaultUtilityLayer;
  90166. },
  90167. enumerable: true,
  90168. configurable: true
  90169. });
  90170. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  90171. /**
  90172. * 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)
  90173. */
  90174. get: function () {
  90175. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  90176. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  90177. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  90178. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  90179. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  90180. });
  90181. }
  90182. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  90183. },
  90184. enumerable: true,
  90185. configurable: true
  90186. });
  90187. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  90188. if (!prePointerInfo.skipOnPointerObservable) {
  90189. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  90190. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  90191. }
  90192. };
  90193. /**
  90194. * Renders the utility layers scene on top of the original scene
  90195. */
  90196. UtilityLayerRenderer.prototype.render = function () {
  90197. this._updateCamera();
  90198. if (this.utilityLayerScene.activeCamera) {
  90199. // Set the camera's scene to utility layers scene
  90200. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  90201. var camera = this.utilityLayerScene.activeCamera;
  90202. camera._scene = this.utilityLayerScene;
  90203. if (camera.leftCamera) {
  90204. camera.leftCamera._scene = this.utilityLayerScene;
  90205. }
  90206. if (camera.rightCamera) {
  90207. camera.rightCamera._scene = this.utilityLayerScene;
  90208. }
  90209. this.utilityLayerScene.render(false);
  90210. // Reset camera's scene back to original
  90211. camera._scene = oldScene;
  90212. if (camera.leftCamera) {
  90213. camera.leftCamera._scene = oldScene;
  90214. }
  90215. if (camera.rightCamera) {
  90216. camera.rightCamera._scene = oldScene;
  90217. }
  90218. }
  90219. };
  90220. /**
  90221. * Disposes of the renderer
  90222. */
  90223. UtilityLayerRenderer.prototype.dispose = function () {
  90224. this.onPointerOutObservable.clear();
  90225. if (this._afterRenderObserver) {
  90226. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  90227. }
  90228. if (this._sceneDisposeObserver) {
  90229. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90230. }
  90231. if (this._originalPointerObserver) {
  90232. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  90233. }
  90234. this.utilityLayerScene.dispose();
  90235. };
  90236. UtilityLayerRenderer.prototype._updateCamera = function () {
  90237. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  90238. };
  90239. UtilityLayerRenderer._DefaultUtilityLayer = null;
  90240. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  90241. return UtilityLayerRenderer;
  90242. }());
  90243. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  90244. })(BABYLON || (BABYLON = {}));
  90245. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  90246. //# sourceMappingURL=babylon.behavior.js.map
  90247. var BABYLON;
  90248. (function (BABYLON) {
  90249. /**
  90250. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  90251. */
  90252. var PointerDragBehavior = /** @class */ (function () {
  90253. /**
  90254. * Creates a pointer drag behavior that can be attached to a mesh
  90255. * @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)
  90256. */
  90257. function PointerDragBehavior(options) {
  90258. /**
  90259. * 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)
  90260. */
  90261. this.maxDragAngle = 0;
  90262. /**
  90263. * @hidden
  90264. */
  90265. this._useAlternatePickedPointAboveMaxDragAngle = false;
  90266. /**
  90267. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  90268. */
  90269. this.currentDraggingPointerID = -1;
  90270. /**
  90271. * If the behavior is currently in a dragging state
  90272. */
  90273. this.dragging = false;
  90274. /**
  90275. * 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)
  90276. */
  90277. this.dragDeltaRatio = 0.2;
  90278. /**
  90279. * If the drag plane orientation should be updated during the dragging (Default: true)
  90280. */
  90281. this.updateDragPlane = true;
  90282. // Debug mode will display drag planes to help visualize behavior
  90283. this._debugMode = false;
  90284. this._moving = false;
  90285. /**
  90286. * Fires each time the attached mesh is dragged with the pointer
  90287. * * delta between last drag position and current drag position in world space
  90288. * * dragDistance along the drag axis
  90289. * * dragPlaneNormal normal of the current drag plane used during the drag
  90290. * * dragPlanePoint in world space where the drag intersects the drag plane
  90291. */
  90292. this.onDragObservable = new BABYLON.Observable();
  90293. /**
  90294. * Fires each time a drag begins (eg. mouse down on mesh)
  90295. */
  90296. this.onDragStartObservable = new BABYLON.Observable();
  90297. /**
  90298. * Fires each time a drag ends (eg. mouse release after drag)
  90299. */
  90300. this.onDragEndObservable = new BABYLON.Observable();
  90301. /**
  90302. * If the attached mesh should be moved when dragged
  90303. */
  90304. this.moveAttached = true;
  90305. /**
  90306. * If the drag behavior will react to drag events (Default: true)
  90307. */
  90308. this.enabled = true;
  90309. /**
  90310. * If camera controls should be detached during the drag
  90311. */
  90312. this.detachCameraControls = true;
  90313. /**
  90314. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  90315. */
  90316. this.useObjectOrienationForDragging = true;
  90317. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90318. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  90319. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  90320. // Variables to avoid instantiation in the below method
  90321. this._pointA = new BABYLON.Vector3(0, 0, 0);
  90322. this._pointB = new BABYLON.Vector3(0, 0, 0);
  90323. this._pointC = new BABYLON.Vector3(0, 0, 0);
  90324. this._lineA = new BABYLON.Vector3(0, 0, 0);
  90325. this._lineB = new BABYLON.Vector3(0, 0, 0);
  90326. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  90327. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  90328. this._options = options ? options : {};
  90329. var optionCount = 0;
  90330. if (this._options.dragAxis) {
  90331. optionCount++;
  90332. }
  90333. if (this._options.dragPlaneNormal) {
  90334. optionCount++;
  90335. }
  90336. if (optionCount > 1) {
  90337. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  90338. }
  90339. }
  90340. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  90341. /**
  90342. * The name of the behavior
  90343. */
  90344. get: function () {
  90345. return "PointerDrag";
  90346. },
  90347. enumerable: true,
  90348. configurable: true
  90349. });
  90350. /**
  90351. * Initializes the behavior
  90352. */
  90353. PointerDragBehavior.prototype.init = function () { };
  90354. /**
  90355. * Attaches the drag behavior the passed in mesh
  90356. * @param ownerNode The mesh that will be dragged around once attached
  90357. */
  90358. PointerDragBehavior.prototype.attach = function (ownerNode) {
  90359. var _this = this;
  90360. this._scene = ownerNode.getScene();
  90361. this._attachedNode = ownerNode;
  90362. // Initialize drag plane to not interfere with existing scene
  90363. if (!PointerDragBehavior._planeScene) {
  90364. if (this._debugMode) {
  90365. PointerDragBehavior._planeScene = this._scene;
  90366. }
  90367. else {
  90368. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  90369. PointerDragBehavior._planeScene.detachControl();
  90370. this._scene.getEngine().scenes.pop();
  90371. this._scene.onDisposeObservable.addOnce(function () {
  90372. PointerDragBehavior._planeScene.dispose();
  90373. PointerDragBehavior._planeScene = null;
  90374. });
  90375. }
  90376. }
  90377. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  90378. // State of the drag
  90379. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  90380. var delta = new BABYLON.Vector3(0, 0, 0);
  90381. var dragLength = 0;
  90382. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  90383. var pickPredicate = function (m) {
  90384. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  90385. };
  90386. var attachedElement = null;
  90387. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  90388. if (!_this.enabled) {
  90389. return;
  90390. }
  90391. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90392. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  90393. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  90394. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  90395. if (pickedPoint) {
  90396. _this.dragging = true;
  90397. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  90398. _this.lastDragPosition.copyFrom(pickedPoint);
  90399. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  90400. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  90401. // Detatch camera controls
  90402. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90403. if (_this._scene.activeCamera.inputs.attachedElement) {
  90404. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  90405. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  90406. }
  90407. else {
  90408. attachedElement = null;
  90409. }
  90410. }
  90411. }
  90412. }
  90413. }
  90414. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  90415. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  90416. _this.releaseDrag();
  90417. // Reattach camera controls
  90418. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90419. _this._scene.activeCamera.attachControl(attachedElement, true);
  90420. }
  90421. }
  90422. }
  90423. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  90424. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90425. _this._moving = true;
  90426. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  90427. if (pickedPoint) {
  90428. if (_this.updateDragPlane) {
  90429. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  90430. }
  90431. // depending on the drag mode option drag accordingly
  90432. if (_this._options.dragAxis) {
  90433. // Convert local drag axis to world
  90434. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  90435. // Project delta drag from the drag plane onto the drag axis
  90436. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  90437. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  90438. _this._worldDragAxis.scaleToRef(dragLength, delta);
  90439. }
  90440. else {
  90441. dragLength = delta.length();
  90442. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  90443. }
  90444. targetPosition.addInPlace(delta);
  90445. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  90446. _this.lastDragPosition.copyFrom(pickedPoint);
  90447. }
  90448. }
  90449. }
  90450. });
  90451. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  90452. if (_this._moving && _this.moveAttached) {
  90453. // Slowly move mesh to avoid jitter
  90454. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  90455. _this._tmpVector.scaleInPlace(0.2);
  90456. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  90457. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  90458. }
  90459. });
  90460. };
  90461. PointerDragBehavior.prototype.releaseDrag = function () {
  90462. this.dragging = false;
  90463. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  90464. this.currentDraggingPointerID = -1;
  90465. this._moving = false;
  90466. };
  90467. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  90468. var _this = this;
  90469. if (!ray) {
  90470. return null;
  90471. }
  90472. // Calculate angle between plane normal and ray
  90473. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  90474. // Correct if ray is casted from oposite side
  90475. if (angle > Math.PI / 2) {
  90476. angle = Math.PI - angle;
  90477. }
  90478. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  90479. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  90480. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  90481. // Invert ray direction along the towards object axis
  90482. this._tmpVector.copyFrom(ray.direction);
  90483. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  90484. this._alternatePickedPoint.normalize();
  90485. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  90486. this._tmpVector.addInPlace(this._alternatePickedPoint);
  90487. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  90488. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  90489. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  90490. this._alternatePickedPoint.addInPlace(this._tmpVector);
  90491. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  90492. return this._alternatePickedPoint;
  90493. }
  90494. else {
  90495. return null;
  90496. }
  90497. }
  90498. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  90499. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  90500. return pickResult.pickedPoint;
  90501. }
  90502. else {
  90503. return null;
  90504. }
  90505. };
  90506. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  90507. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  90508. this._pointA.copyFrom(dragPlanePosition);
  90509. if (this._options.dragAxis) {
  90510. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  90511. // Calculate plane normal in direction of camera but perpendicular to drag axis
  90512. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  90513. ray.origin.subtractToRef(this._pointA, this._pointC);
  90514. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  90515. // Get perpendicular line from direction to camera and drag axis
  90516. this._pointB.subtractToRef(this._pointA, this._lineA);
  90517. this._pointC.subtractToRef(this._pointA, this._lineB);
  90518. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  90519. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  90520. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  90521. this._lookAt.normalize();
  90522. this._dragPlane.position.copyFrom(this._pointA);
  90523. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  90524. this._dragPlane.lookAt(this._lookAt);
  90525. }
  90526. else if (this._options.dragPlaneNormal) {
  90527. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  90528. this._dragPlane.position.copyFrom(this._pointA);
  90529. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  90530. this._dragPlane.lookAt(this._lookAt);
  90531. }
  90532. else {
  90533. this._dragPlane.position.copyFrom(this._pointA);
  90534. this._dragPlane.lookAt(ray.origin);
  90535. }
  90536. this._dragPlane.computeWorldMatrix(true);
  90537. };
  90538. /**
  90539. * Detaches the behavior from the mesh
  90540. */
  90541. PointerDragBehavior.prototype.detach = function () {
  90542. if (this._pointerObserver) {
  90543. this._scene.onPointerObservable.remove(this._pointerObserver);
  90544. }
  90545. if (this._beforeRenderObserver) {
  90546. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90547. }
  90548. };
  90549. return PointerDragBehavior;
  90550. }());
  90551. BABYLON.PointerDragBehavior = PointerDragBehavior;
  90552. })(BABYLON || (BABYLON = {}));
  90553. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  90554. var BABYLON;
  90555. (function (BABYLON) {
  90556. /**
  90557. * A behavior that when attached to a mesh will allow the mesh to be scaled
  90558. */
  90559. var MultiPointerScaleBehavior = /** @class */ (function () {
  90560. function MultiPointerScaleBehavior() {
  90561. this._startDistance = 0;
  90562. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  90563. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  90564. this._sceneRenderObserver = null;
  90565. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  90566. this._dragBehaviorA.moveAttached = false;
  90567. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  90568. this._dragBehaviorB.moveAttached = false;
  90569. }
  90570. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  90571. /**
  90572. * The name of the behavior
  90573. */
  90574. get: function () {
  90575. return "MultiPointerScale";
  90576. },
  90577. enumerable: true,
  90578. configurable: true
  90579. });
  90580. /**
  90581. * Initializes the behavior
  90582. */
  90583. MultiPointerScaleBehavior.prototype.init = function () { };
  90584. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  90585. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  90586. };
  90587. /**
  90588. * Attaches the scale behavior the passed in mesh
  90589. * @param ownerNode The mesh that will be scaled around once attached
  90590. */
  90591. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  90592. var _this = this;
  90593. this._ownerNode = ownerNode;
  90594. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  90595. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  90596. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90597. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  90598. _this._dragBehaviorA.releaseDrag();
  90599. }
  90600. else {
  90601. _this._initialScale.copyFrom(ownerNode.scaling);
  90602. _this._startDistance = _this._getCurrentDistance();
  90603. }
  90604. }
  90605. });
  90606. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  90607. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90608. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  90609. _this._dragBehaviorB.releaseDrag();
  90610. }
  90611. else {
  90612. _this._initialScale.copyFrom(ownerNode.scaling);
  90613. _this._startDistance = _this._getCurrentDistance();
  90614. }
  90615. }
  90616. });
  90617. // Once both drag behaviors are active scale based on the distance between the two pointers
  90618. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  90619. behavior.onDragObservable.add(function () {
  90620. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90621. var ratio = _this._getCurrentDistance() / _this._startDistance;
  90622. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  90623. }
  90624. });
  90625. });
  90626. ownerNode.addBehavior(this._dragBehaviorA);
  90627. ownerNode.addBehavior(this._dragBehaviorB);
  90628. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  90629. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  90630. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90631. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  90632. if (change.length() > 0.01) {
  90633. ownerNode.scaling.addInPlace(change);
  90634. }
  90635. }
  90636. });
  90637. };
  90638. /**
  90639. * Detaches the behavior from the mesh
  90640. */
  90641. MultiPointerScaleBehavior.prototype.detach = function () {
  90642. var _this = this;
  90643. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  90644. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  90645. behavior.onDragStartObservable.clear();
  90646. behavior.onDragObservable.clear();
  90647. _this._ownerNode.removeBehavior(behavior);
  90648. });
  90649. };
  90650. return MultiPointerScaleBehavior;
  90651. }());
  90652. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  90653. })(BABYLON || (BABYLON = {}));
  90654. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  90655. var BABYLON;
  90656. (function (BABYLON) {
  90657. /**
  90658. * 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
  90659. */
  90660. var SixDofDragBehavior = /** @class */ (function () {
  90661. function SixDofDragBehavior() {
  90662. this._sceneRenderObserver = null;
  90663. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  90664. this._moving = false;
  90665. this._startingOrientation = new BABYLON.Quaternion();
  90666. /**
  90667. * 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)
  90668. */
  90669. this.zDragFactor = 3;
  90670. /**
  90671. * If the behavior is currently in a dragging state
  90672. */
  90673. this.dragging = false;
  90674. /**
  90675. * 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)
  90676. */
  90677. this.dragDeltaRatio = 0.2;
  90678. /**
  90679. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  90680. */
  90681. this.currentDraggingPointerID = -1;
  90682. /**
  90683. * If camera controls should be detached during the drag
  90684. */
  90685. this.detachCameraControls = true;
  90686. }
  90687. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  90688. /**
  90689. * The name of the behavior
  90690. */
  90691. get: function () {
  90692. return "SixDofDrag";
  90693. },
  90694. enumerable: true,
  90695. configurable: true
  90696. });
  90697. /**
  90698. * Initializes the behavior
  90699. */
  90700. SixDofDragBehavior.prototype.init = function () { };
  90701. /**
  90702. * Attaches the scale behavior the passed in mesh
  90703. * @param ownerNode The mesh that will be scaled around once attached
  90704. */
  90705. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  90706. var _this = this;
  90707. this._ownerNode = ownerNode;
  90708. this._scene = this._ownerNode.getScene();
  90709. if (!SixDofDragBehavior._virtualScene) {
  90710. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  90711. this._scene.getEngine().scenes.pop();
  90712. }
  90713. var pickedMesh = null;
  90714. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  90715. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  90716. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  90717. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  90718. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  90719. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  90720. var pickPredicate = function (m) {
  90721. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  90722. };
  90723. var attachedElement = null;
  90724. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  90725. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90726. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  90727. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  90728. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  90729. }
  90730. pickedMesh = _this._ownerNode;
  90731. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  90732. // Set position and orientation of the controller
  90733. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  90734. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  90735. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  90736. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90737. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  90738. if (!pickedMesh.rotationQuaternion) {
  90739. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  90740. }
  90741. var oldParent = pickedMesh.parent;
  90742. pickedMesh.setParent(null);
  90743. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  90744. pickedMesh.setParent(oldParent);
  90745. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  90746. // Update state
  90747. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  90748. _this.dragging = true;
  90749. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  90750. // Detatch camera controls
  90751. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90752. if (_this._scene.activeCamera.inputs.attachedElement) {
  90753. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  90754. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  90755. }
  90756. else {
  90757. attachedElement = null;
  90758. }
  90759. }
  90760. }
  90761. }
  90762. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  90763. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  90764. _this.dragging = false;
  90765. _this._moving = false;
  90766. _this.currentDraggingPointerID = -1;
  90767. pickedMesh = null;
  90768. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90769. // Reattach camera controls
  90770. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90771. _this._scene.activeCamera.attachControl(attachedElement, true);
  90772. }
  90773. }
  90774. }
  90775. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  90776. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  90777. var zDragFactor = _this.zDragFactor;
  90778. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  90779. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  90780. zDragFactor = 0;
  90781. }
  90782. // Calculate controller drag distance in controller space
  90783. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  90784. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  90785. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  90786. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  90787. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  90788. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  90789. if (_this._virtualDragMesh.position.z < 0) {
  90790. _this._virtualDragMesh.position.z = 0;
  90791. }
  90792. // Update the controller position
  90793. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  90794. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  90795. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  90796. // Move the virtualObjectsPosition into the picked mesh's space if needed
  90797. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  90798. if (pickedMesh.parent) {
  90799. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  90800. }
  90801. if (!_this._moving) {
  90802. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  90803. }
  90804. _this._moving = true;
  90805. }
  90806. }
  90807. });
  90808. var tmpQuaternion = new BABYLON.Quaternion();
  90809. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  90810. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  90811. if (_this.dragging && _this._moving && pickedMesh) {
  90812. // Slowly move mesh to avoid jitter
  90813. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  90814. // Get change in rotation
  90815. tmpQuaternion.copyFrom(_this._startingOrientation);
  90816. tmpQuaternion.x = -tmpQuaternion.x;
  90817. tmpQuaternion.y = -tmpQuaternion.y;
  90818. tmpQuaternion.z = -tmpQuaternion.z;
  90819. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  90820. // Convert change in rotation to only y axis rotation
  90821. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  90822. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  90823. // Slowly move mesh to avoid jitter
  90824. var oldParent = pickedMesh.parent;
  90825. pickedMesh.setParent(null);
  90826. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  90827. pickedMesh.setParent(oldParent);
  90828. }
  90829. });
  90830. };
  90831. /**
  90832. * Detaches the behavior from the mesh
  90833. */
  90834. SixDofDragBehavior.prototype.detach = function () {
  90835. if (this._scene) {
  90836. this._scene.onPointerObservable.remove(this._pointerObserver);
  90837. }
  90838. if (this._ownerNode) {
  90839. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  90840. }
  90841. if (this._virtualOriginMesh) {
  90842. this._virtualOriginMesh.dispose();
  90843. }
  90844. if (this._virtualDragMesh) {
  90845. this._virtualDragMesh.dispose();
  90846. }
  90847. };
  90848. return SixDofDragBehavior;
  90849. }());
  90850. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  90851. })(BABYLON || (BABYLON = {}));
  90852. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  90853. var BABYLON;
  90854. (function (BABYLON) {
  90855. /**
  90856. * @hidden
  90857. */
  90858. var FaceDirectionInfo = /** @class */ (function () {
  90859. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  90860. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  90861. if (diff === void 0) { diff = 0; }
  90862. if (ignore === void 0) { ignore = false; }
  90863. this.direction = direction;
  90864. this.rotatedDirection = rotatedDirection;
  90865. this.diff = diff;
  90866. this.ignore = ignore;
  90867. }
  90868. return FaceDirectionInfo;
  90869. }());
  90870. /**
  90871. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  90872. */
  90873. var AttachToBoxBehavior = /** @class */ (function () {
  90874. /**
  90875. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  90876. * @param ui The transform node that should be attched to the mesh
  90877. */
  90878. function AttachToBoxBehavior(ui) {
  90879. this.ui = ui;
  90880. /**
  90881. * The name of the behavior
  90882. */
  90883. this.name = "AttachToBoxBehavior";
  90884. /**
  90885. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  90886. */
  90887. this.distanceAwayFromFace = 0.15;
  90888. /**
  90889. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  90890. */
  90891. this.distanceAwayFromBottomOfFace = 0.15;
  90892. 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))];
  90893. this._tmpMatrix = new BABYLON.Matrix();
  90894. this._tmpVector = new BABYLON.Vector3();
  90895. this._zeroVector = BABYLON.Vector3.Zero();
  90896. this._lookAtTmpMatrix = new BABYLON.Matrix();
  90897. /* Does nothing */
  90898. }
  90899. /**
  90900. * Initializes the behavior
  90901. */
  90902. AttachToBoxBehavior.prototype.init = function () {
  90903. /* Does nothing */
  90904. };
  90905. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  90906. var _this = this;
  90907. // Go over each face and calculate the angle between the face's normal and targetDirection
  90908. this._faceVectors.forEach(function (v) {
  90909. if (!_this._target.rotationQuaternion) {
  90910. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  90911. }
  90912. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  90913. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  90914. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  90915. });
  90916. // Return the face information of the one with the normal closeset to target direction
  90917. return this._faceVectors.reduce(function (min, p) {
  90918. if (min.ignore) {
  90919. return p;
  90920. }
  90921. else if (p.ignore) {
  90922. return min;
  90923. }
  90924. else {
  90925. return min.diff < p.diff ? min : p;
  90926. }
  90927. }, this._faceVectors[0]);
  90928. };
  90929. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  90930. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  90931. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  90932. this._lookAtTmpMatrix.invert();
  90933. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  90934. };
  90935. /**
  90936. * Attaches the AttachToBoxBehavior to the passed in mesh
  90937. * @param target The mesh that the specified node will be attached to
  90938. */
  90939. AttachToBoxBehavior.prototype.attach = function (target) {
  90940. var _this = this;
  90941. this._target = target;
  90942. this._scene = this._target.getScene();
  90943. // Every frame, update the app bars position
  90944. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  90945. if (!_this._scene.activeCamera) {
  90946. return;
  90947. }
  90948. // Find the face closest to the cameras position
  90949. var cameraPos = _this._scene.activeCamera.position;
  90950. if (_this._scene.activeCamera.devicePosition) {
  90951. cameraPos = _this._scene.activeCamera.devicePosition;
  90952. }
  90953. var facing = _this._closestFace(cameraPos.subtract(target.position));
  90954. if (_this._scene.activeCamera.leftCamera) {
  90955. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  90956. }
  90957. else {
  90958. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  90959. }
  90960. // Get camera up direction
  90961. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  90962. // Ignore faces to not select a parrelel face for the up vector of the UI
  90963. _this._faceVectors.forEach(function (v) {
  90964. if (facing.direction.x && v.direction.x) {
  90965. v.ignore = true;
  90966. }
  90967. if (facing.direction.y && v.direction.y) {
  90968. v.ignore = true;
  90969. }
  90970. if (facing.direction.z && v.direction.z) {
  90971. v.ignore = true;
  90972. }
  90973. });
  90974. var facingUp = _this._closestFace(_this._tmpVector);
  90975. // Unignore faces
  90976. _this._faceVectors.forEach(function (v) {
  90977. v.ignore = false;
  90978. });
  90979. // Position the app bar on that face
  90980. _this.ui.position.copyFrom(target.position);
  90981. if (facing.direction.x) {
  90982. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90983. _this.ui.position.addInPlace(_this._tmpVector);
  90984. }
  90985. if (facing.direction.y) {
  90986. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90987. _this.ui.position.addInPlace(_this._tmpVector);
  90988. }
  90989. if (facing.direction.z) {
  90990. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  90991. _this.ui.position.addInPlace(_this._tmpVector);
  90992. }
  90993. // Rotate to be oriented properly to the camera
  90994. if (!_this.ui.rotationQuaternion) {
  90995. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  90996. }
  90997. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  90998. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  90999. // Place ui the correct distance from the bottom of the mesh
  91000. if (facingUp.direction.x) {
  91001. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  91002. }
  91003. if (facingUp.direction.y) {
  91004. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  91005. }
  91006. if (facingUp.direction.z) {
  91007. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  91008. }
  91009. _this.ui.position.addInPlace(_this._tmpVector);
  91010. });
  91011. };
  91012. /**
  91013. * Detaches the behavior from the mesh
  91014. */
  91015. AttachToBoxBehavior.prototype.detach = function () {
  91016. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  91017. };
  91018. return AttachToBoxBehavior;
  91019. }());
  91020. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  91021. })(BABYLON || (BABYLON = {}));
  91022. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  91023. var BABYLON;
  91024. (function (BABYLON) {
  91025. /**
  91026. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  91027. */
  91028. var Gizmo = /** @class */ (function () {
  91029. /**
  91030. * Creates a gizmo
  91031. * @param gizmoLayer The utility layer the gizmo will be added to
  91032. */
  91033. function Gizmo(
  91034. /** The utility layer the gizmo will be added to */
  91035. gizmoLayer) {
  91036. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91037. var _this = this;
  91038. this.gizmoLayer = gizmoLayer;
  91039. this._scaleFactor = 3;
  91040. this._tmpMatrix = new BABYLON.Matrix();
  91041. /**
  91042. * If a custom mesh has been set (Default: false)
  91043. */
  91044. this._customMeshSet = false;
  91045. /**
  91046. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  91047. */
  91048. this.updateGizmoRotationToMatchAttachedMesh = true;
  91049. /**
  91050. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  91051. */
  91052. this.updateGizmoPositionToMatchAttachedMesh = true;
  91053. /**
  91054. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  91055. */
  91056. this._updateScale = true;
  91057. this._interactionsEnabled = true;
  91058. this._tempVector = new BABYLON.Vector3();
  91059. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  91060. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  91061. _this._update();
  91062. });
  91063. this.attachedMesh = null;
  91064. }
  91065. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  91066. /**
  91067. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  91068. * * When set, interactions will be enabled
  91069. */
  91070. get: function () {
  91071. return this._attachedMesh;
  91072. },
  91073. set: function (value) {
  91074. this._attachedMesh = value;
  91075. this._rootMesh.setEnabled(value ? true : false);
  91076. this._attachedMeshChanged(value);
  91077. },
  91078. enumerable: true,
  91079. configurable: true
  91080. });
  91081. /**
  91082. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  91083. * @param mesh The mesh to replace the default mesh of the gizmo
  91084. */
  91085. Gizmo.prototype.setCustomMesh = function (mesh) {
  91086. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  91087. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  91088. }
  91089. this._rootMesh.getChildMeshes().forEach(function (c) {
  91090. c.dispose();
  91091. });
  91092. mesh.parent = this._rootMesh;
  91093. this._customMeshSet = true;
  91094. };
  91095. Gizmo.prototype._attachedMeshChanged = function (value) {
  91096. };
  91097. /**
  91098. * @hidden
  91099. * Updates the gizmo to match the attached mesh's position/rotation
  91100. */
  91101. Gizmo.prototype._update = function () {
  91102. if (this.attachedMesh) {
  91103. if (this.updateGizmoRotationToMatchAttachedMesh) {
  91104. if (!this._rootMesh.rotationQuaternion) {
  91105. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  91106. }
  91107. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  91108. this._tempVector.copyFrom(this.attachedMesh.scaling);
  91109. if (this.attachedMesh.scaling.x < 0) {
  91110. this.attachedMesh.scaling.x *= -1;
  91111. }
  91112. if (this.attachedMesh.scaling.y < 0) {
  91113. this.attachedMesh.scaling.y *= -1;
  91114. }
  91115. if (this.attachedMesh.scaling.z < 0) {
  91116. this.attachedMesh.scaling.z *= -1;
  91117. }
  91118. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  91119. this.attachedMesh.scaling.copyFrom(this._tempVector);
  91120. this.attachedMesh.computeWorldMatrix();
  91121. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  91122. }
  91123. else if (this._rootMesh.rotationQuaternion) {
  91124. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  91125. }
  91126. if (this.updateGizmoPositionToMatchAttachedMesh) {
  91127. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  91128. }
  91129. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  91130. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  91131. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  91132. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  91133. }
  91134. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  91135. var dist = this._tempVector.length() / this._scaleFactor;
  91136. this._rootMesh.scaling.set(dist, dist, dist);
  91137. }
  91138. }
  91139. };
  91140. /**
  91141. * Disposes of the gizmo
  91142. */
  91143. Gizmo.prototype.dispose = function () {
  91144. this._rootMesh.dispose();
  91145. if (this._beforeRenderObserver) {
  91146. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  91147. }
  91148. };
  91149. return Gizmo;
  91150. }());
  91151. BABYLON.Gizmo = Gizmo;
  91152. })(BABYLON || (BABYLON = {}));
  91153. //# sourceMappingURL=babylon.gizmo.js.map
  91154. var BABYLON;
  91155. (function (BABYLON) {
  91156. /**
  91157. * Single axis drag gizmo
  91158. */
  91159. var AxisDragGizmo = /** @class */ (function (_super) {
  91160. __extends(AxisDragGizmo, _super);
  91161. /**
  91162. * Creates an AxisDragGizmo
  91163. * @param gizmoLayer The utility layer the gizmo will be added to
  91164. * @param dragAxis The axis which the gizmo will be able to drag on
  91165. * @param color The color of the gizmo
  91166. */
  91167. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  91168. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91169. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91170. var _this = _super.call(this, gizmoLayer) || this;
  91171. _this._pointerObserver = null;
  91172. /**
  91173. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  91174. */
  91175. _this.snapDistance = 0;
  91176. /**
  91177. * Event that fires each time the gizmo snaps to a new location.
  91178. * * snapDistance is the the change in distance
  91179. */
  91180. _this.onSnapObservable = new BABYLON.Observable();
  91181. // Create Material
  91182. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91183. coloredMaterial.disableLighting = true;
  91184. coloredMaterial.emissiveColor = color;
  91185. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91186. hoverMaterial.disableLighting = true;
  91187. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  91188. // Build mesh on root node
  91189. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91190. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  91191. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  91192. arrowTail.color = coloredMaterial.emissiveColor;
  91193. arrow.addChild(arrowMesh);
  91194. arrow.addChild(arrowTail);
  91195. // Position arrow pointing in its drag axis
  91196. arrowMesh.scaling.scaleInPlace(0.05);
  91197. arrowMesh.material = coloredMaterial;
  91198. arrowMesh.rotation.x = Math.PI / 2;
  91199. arrowMesh.position.z += 0.3;
  91200. arrowTail.scaling.scaleInPlace(0.2);
  91201. arrowTail.rotation.x = Math.PI / 2;
  91202. arrowTail.material = coloredMaterial;
  91203. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  91204. _this._rootMesh.addChild(arrow);
  91205. var currentSnapDragDistance = 0;
  91206. var tmpVector = new BABYLON.Vector3();
  91207. var tmpSnapEvent = { snapDistance: 0 };
  91208. // Add drag behavior to handle events when the gizmo is dragged
  91209. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  91210. _this.dragBehavior.moveAttached = false;
  91211. _this._rootMesh.addBehavior(_this.dragBehavior);
  91212. var localDelta = new BABYLON.Vector3();
  91213. var tmpMatrix = new BABYLON.Matrix();
  91214. _this.dragBehavior.onDragObservable.add(function (event) {
  91215. if (_this.attachedMesh) {
  91216. // Convert delta to local translation if it has a parent
  91217. if (_this.attachedMesh.parent) {
  91218. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  91219. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  91220. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  91221. }
  91222. else {
  91223. localDelta.copyFrom(event.delta);
  91224. }
  91225. // Snapping logic
  91226. if (_this.snapDistance == 0) {
  91227. _this.attachedMesh.position.addInPlace(localDelta);
  91228. }
  91229. else {
  91230. currentSnapDragDistance += event.dragDistance;
  91231. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  91232. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  91233. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  91234. localDelta.normalizeToRef(tmpVector);
  91235. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  91236. _this.attachedMesh.position.addInPlace(tmpVector);
  91237. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  91238. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  91239. }
  91240. }
  91241. }
  91242. });
  91243. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91244. if (_this._customMeshSet) {
  91245. return;
  91246. }
  91247. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  91248. var material = isHovered ? hoverMaterial : coloredMaterial;
  91249. _this._rootMesh.getChildMeshes().forEach(function (m) {
  91250. m.material = material;
  91251. if (m.color) {
  91252. m.color = material.emissiveColor;
  91253. }
  91254. });
  91255. });
  91256. return _this;
  91257. }
  91258. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  91259. if (this.dragBehavior) {
  91260. this.dragBehavior.enabled = value ? true : false;
  91261. }
  91262. };
  91263. /**
  91264. * Disposes of the gizmo
  91265. */
  91266. AxisDragGizmo.prototype.dispose = function () {
  91267. this.onSnapObservable.clear();
  91268. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91269. this.dragBehavior.detach();
  91270. _super.prototype.dispose.call(this);
  91271. };
  91272. return AxisDragGizmo;
  91273. }(BABYLON.Gizmo));
  91274. BABYLON.AxisDragGizmo = AxisDragGizmo;
  91275. })(BABYLON || (BABYLON = {}));
  91276. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  91277. var BABYLON;
  91278. (function (BABYLON) {
  91279. /**
  91280. * Single axis scale gizmo
  91281. */
  91282. var AxisScaleGizmo = /** @class */ (function (_super) {
  91283. __extends(AxisScaleGizmo, _super);
  91284. /**
  91285. * Creates an AxisScaleGizmo
  91286. * @param gizmoLayer The utility layer the gizmo will be added to
  91287. * @param dragAxis The axis which the gizmo will be able to scale on
  91288. * @param color The color of the gizmo
  91289. */
  91290. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  91291. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91292. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91293. var _this = _super.call(this, gizmoLayer) || this;
  91294. _this._pointerObserver = null;
  91295. /**
  91296. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  91297. */
  91298. _this.snapDistance = 0;
  91299. /**
  91300. * Event that fires each time the gizmo snaps to a new location.
  91301. * * snapDistance is the the change in distance
  91302. */
  91303. _this.onSnapObservable = new BABYLON.Observable();
  91304. /**
  91305. * If the scaling operation should be done on all axis (default: false)
  91306. */
  91307. _this.uniformScaling = false;
  91308. // Create Material
  91309. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91310. _this._coloredMaterial.disableLighting = true;
  91311. _this._coloredMaterial.emissiveColor = color;
  91312. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91313. hoverMaterial.disableLighting = true;
  91314. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  91315. // Build mesh on root node
  91316. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91317. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  91318. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  91319. arrowTail.color = _this._coloredMaterial.emissiveColor;
  91320. arrow.addChild(arrowMesh);
  91321. arrow.addChild(arrowTail);
  91322. // Position arrow pointing in its drag axis
  91323. arrowMesh.scaling.scaleInPlace(0.1);
  91324. arrowMesh.material = _this._coloredMaterial;
  91325. arrowMesh.rotation.x = Math.PI / 2;
  91326. arrowMesh.position.z += 0.3;
  91327. arrowTail.scaling.scaleInPlace(0.2);
  91328. arrowTail.rotation.x = Math.PI / 2;
  91329. arrowTail.material = _this._coloredMaterial;
  91330. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  91331. _this._rootMesh.addChild(arrow);
  91332. // Add drag behavior to handle events when the gizmo is dragged
  91333. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  91334. _this.dragBehavior.moveAttached = false;
  91335. _this._rootMesh.addBehavior(_this.dragBehavior);
  91336. var currentSnapDragDistance = 0;
  91337. var tmpVector = new BABYLON.Vector3();
  91338. var tmpSnapEvent = { snapDistance: 0 };
  91339. _this.dragBehavior.onDragObservable.add(function (event) {
  91340. if (_this.attachedMesh) {
  91341. // Snapping logic
  91342. var snapped = false;
  91343. var dragSteps = 0;
  91344. if (_this.uniformScaling) {
  91345. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  91346. if (tmpVector.y < 0) {
  91347. tmpVector.scaleInPlace(-1);
  91348. }
  91349. }
  91350. else {
  91351. tmpVector.copyFrom(dragAxis);
  91352. }
  91353. if (_this.snapDistance == 0) {
  91354. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  91355. }
  91356. else {
  91357. currentSnapDragDistance += event.dragDistance;
  91358. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  91359. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  91360. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  91361. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  91362. snapped = true;
  91363. }
  91364. else {
  91365. tmpVector.scaleInPlace(0);
  91366. }
  91367. }
  91368. _this.attachedMesh.scaling.addInPlace(tmpVector);
  91369. if (snapped) {
  91370. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  91371. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  91372. }
  91373. }
  91374. });
  91375. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91376. if (_this._customMeshSet) {
  91377. return;
  91378. }
  91379. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  91380. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  91381. _this._rootMesh.getChildMeshes().forEach(function (m) {
  91382. m.material = material;
  91383. if (m.color) {
  91384. m.color = material.emissiveColor;
  91385. }
  91386. });
  91387. });
  91388. return _this;
  91389. }
  91390. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  91391. if (this.dragBehavior) {
  91392. this.dragBehavior.enabled = value ? true : false;
  91393. }
  91394. };
  91395. /**
  91396. * Disposes of the gizmo
  91397. */
  91398. AxisScaleGizmo.prototype.dispose = function () {
  91399. this.onSnapObservable.clear();
  91400. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91401. this.dragBehavior.detach();
  91402. _super.prototype.dispose.call(this);
  91403. };
  91404. /**
  91405. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  91406. * @param mesh The mesh to replace the default mesh of the gizmo
  91407. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  91408. */
  91409. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  91410. var _this = this;
  91411. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  91412. _super.prototype.setCustomMesh.call(this, mesh);
  91413. if (useGizmoMaterial) {
  91414. this._rootMesh.getChildMeshes().forEach(function (m) {
  91415. m.material = _this._coloredMaterial;
  91416. if (m.color) {
  91417. m.color = _this._coloredMaterial.emissiveColor;
  91418. }
  91419. });
  91420. this._customMeshSet = false;
  91421. }
  91422. };
  91423. return AxisScaleGizmo;
  91424. }(BABYLON.Gizmo));
  91425. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  91426. })(BABYLON || (BABYLON = {}));
  91427. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  91428. var BABYLON;
  91429. (function (BABYLON) {
  91430. /**
  91431. * Single plane rotation gizmo
  91432. */
  91433. var PlaneRotationGizmo = /** @class */ (function (_super) {
  91434. __extends(PlaneRotationGizmo, _super);
  91435. /**
  91436. * Creates a PlaneRotationGizmo
  91437. * @param gizmoLayer The utility layer the gizmo will be added to
  91438. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  91439. * @param color The color of the gizmo
  91440. */
  91441. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  91442. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91443. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91444. var _this = _super.call(this, gizmoLayer) || this;
  91445. _this._pointerObserver = null;
  91446. /**
  91447. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  91448. */
  91449. _this.snapDistance = 0;
  91450. /**
  91451. * Event that fires each time the gizmo snaps to a new location.
  91452. * * snapDistance is the the change in distance
  91453. */
  91454. _this.onSnapObservable = new BABYLON.Observable();
  91455. // Create Material
  91456. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91457. coloredMaterial.disableLighting = true;
  91458. coloredMaterial.emissiveColor = color;
  91459. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91460. hoverMaterial.disableLighting = true;
  91461. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  91462. // Build mesh on root node
  91463. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91464. // Create circle out of lines
  91465. var tessellation = 20;
  91466. var radius = 2;
  91467. var points = new Array();
  91468. for (var i = 0; i < tessellation; i++) {
  91469. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  91470. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  91471. }
  91472. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  91473. rotationMesh.color = coloredMaterial.emissiveColor;
  91474. // Position arrow pointing in its drag axis
  91475. rotationMesh.scaling.scaleInPlace(0.1);
  91476. rotationMesh.material = coloredMaterial;
  91477. rotationMesh.rotation.x = Math.PI / 2;
  91478. parentMesh.addChild(rotationMesh);
  91479. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  91480. _this._rootMesh.addChild(parentMesh);
  91481. // Add drag behavior to handle events when the gizmo is dragged
  91482. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  91483. _this.dragBehavior.moveAttached = false;
  91484. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  91485. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  91486. _this._rootMesh.addBehavior(_this.dragBehavior);
  91487. var lastDragPosition = new BABYLON.Vector3();
  91488. _this.dragBehavior.onDragStartObservable.add(function (e) {
  91489. if (_this.attachedMesh) {
  91490. lastDragPosition.copyFrom(e.dragPlanePoint);
  91491. }
  91492. });
  91493. var rotationMatrix = new BABYLON.Matrix();
  91494. var planeNormalTowardsCamera = new BABYLON.Vector3();
  91495. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  91496. var tmpSnapEvent = { snapDistance: 0 };
  91497. var currentSnapDragDistance = 0;
  91498. var tmpMatrix = new BABYLON.Matrix();
  91499. var tmpVector = new BABYLON.Vector3();
  91500. var amountToRotate = new BABYLON.Quaternion();
  91501. _this.dragBehavior.onDragObservable.add(function (event) {
  91502. if (_this.attachedMesh) {
  91503. if (!_this.attachedMesh.rotationQuaternion) {
  91504. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  91505. }
  91506. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  91507. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  91508. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  91509. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  91510. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  91511. var angle = Math.atan2(cross.length(), dot);
  91512. planeNormalTowardsCamera.copyFrom(planeNormal);
  91513. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  91514. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  91515. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  91516. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  91517. }
  91518. // Flip up vector depending on which side the camera is on
  91519. if (gizmoLayer.utilityLayerScene.activeCamera) {
  91520. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  91521. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  91522. planeNormalTowardsCamera.scaleInPlace(-1);
  91523. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  91524. }
  91525. }
  91526. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  91527. if (halfCircleSide)
  91528. angle = -angle;
  91529. // Snapping logic
  91530. var snapped = false;
  91531. if (_this.snapDistance != 0) {
  91532. currentSnapDragDistance += angle;
  91533. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  91534. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  91535. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  91536. angle = _this.snapDistance * dragSteps;
  91537. snapped = true;
  91538. }
  91539. else {
  91540. angle = 0;
  91541. }
  91542. }
  91543. // If the mesh has a parent, convert needed world rotation to local rotation
  91544. tmpMatrix.reset();
  91545. if (_this.attachedMesh.parent) {
  91546. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  91547. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  91548. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  91549. }
  91550. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  91551. var quaternionCoefficient = Math.sin(angle / 2);
  91552. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  91553. // 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
  91554. if (tmpMatrix.determinant() > 0) {
  91555. amountToRotate.toEulerAnglesToRef(tmpVector);
  91556. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  91557. }
  91558. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  91559. // Rotate selected mesh quaternion over fixed axis
  91560. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  91561. }
  91562. else {
  91563. // Rotate selected mesh quaternion over rotated axis
  91564. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  91565. }
  91566. lastDragPosition.copyFrom(event.dragPlanePoint);
  91567. if (snapped) {
  91568. tmpSnapEvent.snapDistance = angle;
  91569. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  91570. }
  91571. }
  91572. });
  91573. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91574. if (_this._customMeshSet) {
  91575. return;
  91576. }
  91577. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  91578. var material = isHovered ? hoverMaterial : coloredMaterial;
  91579. _this._rootMesh.getChildMeshes().forEach(function (m) {
  91580. m.material = material;
  91581. if (m.color) {
  91582. m.color = material.emissiveColor;
  91583. }
  91584. });
  91585. });
  91586. return _this;
  91587. }
  91588. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  91589. if (this.dragBehavior) {
  91590. this.dragBehavior.enabled = value ? true : false;
  91591. }
  91592. };
  91593. /**
  91594. * Disposes of the gizmo
  91595. */
  91596. PlaneRotationGizmo.prototype.dispose = function () {
  91597. this.onSnapObservable.clear();
  91598. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91599. this.dragBehavior.detach();
  91600. _super.prototype.dispose.call(this);
  91601. };
  91602. return PlaneRotationGizmo;
  91603. }(BABYLON.Gizmo));
  91604. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  91605. })(BABYLON || (BABYLON = {}));
  91606. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  91607. var BABYLON;
  91608. (function (BABYLON) {
  91609. /**
  91610. * Gizmo that enables dragging a mesh along 3 axis
  91611. */
  91612. var PositionGizmo = /** @class */ (function (_super) {
  91613. __extends(PositionGizmo, _super);
  91614. /**
  91615. * Creates a PositionGizmo
  91616. * @param gizmoLayer The utility layer the gizmo will be added to
  91617. */
  91618. function PositionGizmo(gizmoLayer) {
  91619. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91620. var _this = _super.call(this, gizmoLayer) || this;
  91621. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91622. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91623. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91624. _this.attachedMesh = null;
  91625. return _this;
  91626. }
  91627. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  91628. set: function (mesh) {
  91629. if (this.xGizmo) {
  91630. this.xGizmo.attachedMesh = mesh;
  91631. this.yGizmo.attachedMesh = mesh;
  91632. this.zGizmo.attachedMesh = mesh;
  91633. }
  91634. },
  91635. enumerable: true,
  91636. configurable: true
  91637. });
  91638. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91639. get: function () {
  91640. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91641. },
  91642. set: function (value) {
  91643. if (this.xGizmo) {
  91644. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91645. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91646. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91647. }
  91648. },
  91649. enumerable: true,
  91650. configurable: true
  91651. });
  91652. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  91653. get: function () {
  91654. return this.xGizmo.snapDistance;
  91655. },
  91656. /**
  91657. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  91658. */
  91659. set: function (value) {
  91660. if (this.xGizmo) {
  91661. this.xGizmo.snapDistance = value;
  91662. this.yGizmo.snapDistance = value;
  91663. this.zGizmo.snapDistance = value;
  91664. }
  91665. },
  91666. enumerable: true,
  91667. configurable: true
  91668. });
  91669. /**
  91670. * Disposes of the gizmo
  91671. */
  91672. PositionGizmo.prototype.dispose = function () {
  91673. this.xGizmo.dispose();
  91674. this.yGizmo.dispose();
  91675. this.zGizmo.dispose();
  91676. };
  91677. /**
  91678. * CustomMeshes are not supported by this gizmo
  91679. * @param mesh The mesh to replace the default mesh of the gizmo
  91680. */
  91681. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  91682. 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)");
  91683. };
  91684. return PositionGizmo;
  91685. }(BABYLON.Gizmo));
  91686. BABYLON.PositionGizmo = PositionGizmo;
  91687. })(BABYLON || (BABYLON = {}));
  91688. //# sourceMappingURL=babylon.positionGizmo.js.map
  91689. var BABYLON;
  91690. (function (BABYLON) {
  91691. /**
  91692. * Gizmo that enables rotating a mesh along 3 axis
  91693. */
  91694. var RotationGizmo = /** @class */ (function (_super) {
  91695. __extends(RotationGizmo, _super);
  91696. /**
  91697. * Creates a RotationGizmo
  91698. * @param gizmoLayer The utility layer the gizmo will be added to
  91699. */
  91700. function RotationGizmo(gizmoLayer) {
  91701. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91702. var _this = _super.call(this, gizmoLayer) || this;
  91703. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91704. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91705. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91706. _this.attachedMesh = null;
  91707. return _this;
  91708. }
  91709. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  91710. set: function (mesh) {
  91711. if (this.xGizmo) {
  91712. this.xGizmo.attachedMesh = mesh;
  91713. this.yGizmo.attachedMesh = mesh;
  91714. this.zGizmo.attachedMesh = mesh;
  91715. }
  91716. },
  91717. enumerable: true,
  91718. configurable: true
  91719. });
  91720. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91721. get: function () {
  91722. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91723. },
  91724. set: function (value) {
  91725. if (this.xGizmo) {
  91726. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91727. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91728. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91729. }
  91730. },
  91731. enumerable: true,
  91732. configurable: true
  91733. });
  91734. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  91735. get: function () {
  91736. return this.xGizmo.snapDistance;
  91737. },
  91738. /**
  91739. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  91740. */
  91741. set: function (value) {
  91742. if (this.xGizmo) {
  91743. this.xGizmo.snapDistance = value;
  91744. this.yGizmo.snapDistance = value;
  91745. this.zGizmo.snapDistance = value;
  91746. }
  91747. },
  91748. enumerable: true,
  91749. configurable: true
  91750. });
  91751. /**
  91752. * Disposes of the gizmo
  91753. */
  91754. RotationGizmo.prototype.dispose = function () {
  91755. this.xGizmo.dispose();
  91756. this.yGizmo.dispose();
  91757. this.zGizmo.dispose();
  91758. };
  91759. /**
  91760. * CustomMeshes are not supported by this gizmo
  91761. * @param mesh The mesh to replace the default mesh of the gizmo
  91762. */
  91763. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  91764. 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)");
  91765. };
  91766. return RotationGizmo;
  91767. }(BABYLON.Gizmo));
  91768. BABYLON.RotationGizmo = RotationGizmo;
  91769. })(BABYLON || (BABYLON = {}));
  91770. //# sourceMappingURL=babylon.rotationGizmo.js.map
  91771. var BABYLON;
  91772. (function (BABYLON) {
  91773. /**
  91774. * Gizmo that enables scaling a mesh along 3 axis
  91775. */
  91776. var ScaleGizmo = /** @class */ (function (_super) {
  91777. __extends(ScaleGizmo, _super);
  91778. /**
  91779. * Creates a ScaleGizmo
  91780. * @param gizmoLayer The utility layer the gizmo will be added to
  91781. */
  91782. function ScaleGizmo(gizmoLayer) {
  91783. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91784. var _this = _super.call(this, gizmoLayer) || this;
  91785. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91786. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91787. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91788. // Create uniform scale gizmo
  91789. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  91790. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91791. _this._uniformGizmo.uniformScaling = true;
  91792. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  91793. octahedron.scaling.scaleInPlace(0.02);
  91794. _this._uniformGizmo.setCustomMesh(octahedron, true);
  91795. _this.attachedMesh = null;
  91796. return _this;
  91797. }
  91798. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  91799. set: function (mesh) {
  91800. if (this.xGizmo) {
  91801. this.xGizmo.attachedMesh = mesh;
  91802. this.yGizmo.attachedMesh = mesh;
  91803. this.zGizmo.attachedMesh = mesh;
  91804. this._uniformGizmo.attachedMesh = mesh;
  91805. }
  91806. },
  91807. enumerable: true,
  91808. configurable: true
  91809. });
  91810. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91811. get: function () {
  91812. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91813. },
  91814. set: function (value) {
  91815. if (this.xGizmo) {
  91816. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91817. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91818. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91819. }
  91820. },
  91821. enumerable: true,
  91822. configurable: true
  91823. });
  91824. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  91825. get: function () {
  91826. return this.xGizmo.snapDistance;
  91827. },
  91828. /**
  91829. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  91830. */
  91831. set: function (value) {
  91832. if (this.xGizmo) {
  91833. this.xGizmo.snapDistance = value;
  91834. this.yGizmo.snapDistance = value;
  91835. this.zGizmo.snapDistance = value;
  91836. this._uniformGizmo.snapDistance = value;
  91837. }
  91838. },
  91839. enumerable: true,
  91840. configurable: true
  91841. });
  91842. /**
  91843. * Disposes of the gizmo
  91844. */
  91845. ScaleGizmo.prototype.dispose = function () {
  91846. this.xGizmo.dispose();
  91847. this.yGizmo.dispose();
  91848. this.zGizmo.dispose();
  91849. this._uniformGizmo.dispose();
  91850. };
  91851. return ScaleGizmo;
  91852. }(BABYLON.Gizmo));
  91853. BABYLON.ScaleGizmo = ScaleGizmo;
  91854. })(BABYLON || (BABYLON = {}));
  91855. //# sourceMappingURL=babylon.scaleGizmo.js.map
  91856. var BABYLON;
  91857. (function (BABYLON) {
  91858. /**
  91859. * Bounding box gizmo
  91860. */
  91861. var BoundingBoxGizmo = /** @class */ (function (_super) {
  91862. __extends(BoundingBoxGizmo, _super);
  91863. /**
  91864. * Creates an BoundingBoxGizmo
  91865. * @param gizmoLayer The utility layer the gizmo will be added to
  91866. * @param color The color of the gizmo
  91867. */
  91868. function BoundingBoxGizmo(color, gizmoLayer) {
  91869. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91870. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  91871. var _this = _super.call(this, gizmoLayer) || this;
  91872. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  91873. _this._renderObserver = null;
  91874. _this._pointerObserver = null;
  91875. _this._scaleDragSpeed = 0.2;
  91876. _this._tmpQuaternion = new BABYLON.Quaternion();
  91877. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  91878. /**
  91879. * 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)
  91880. */
  91881. _this.ignoreChildren = false;
  91882. /**
  91883. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  91884. */
  91885. _this.rotationSphereSize = 0.1;
  91886. /**
  91887. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  91888. */
  91889. _this.scaleBoxSize = 0.1;
  91890. /**
  91891. * 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)
  91892. */
  91893. _this.fixedDragMeshScreenSize = false;
  91894. /**
  91895. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  91896. */
  91897. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  91898. /**
  91899. * Fired when a rotation sphere or scale box is dragged
  91900. */
  91901. _this.onDragStartObservable = new BABYLON.Observable();
  91902. /**
  91903. * Fired when a scale box is dragged
  91904. */
  91905. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  91906. /**
  91907. * Fired when a scale box drag is ended
  91908. */
  91909. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  91910. /**
  91911. * Fired when a rotation sphere is dragged
  91912. */
  91913. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  91914. /**
  91915. * Fired when a rotation sphere drag is ended
  91916. */
  91917. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  91918. _this._existingMeshScale = new BABYLON.Vector3();
  91919. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  91920. _this._updateScale = false;
  91921. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  91922. // Create Materials
  91923. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91924. coloredMaterial.disableLighting = true;
  91925. coloredMaterial.emissiveColor = color;
  91926. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91927. hoverColoredMaterial.disableLighting = true;
  91928. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  91929. // Build bounding box out of lines
  91930. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91931. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  91932. var lines = [];
  91933. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  91934. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  91935. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  91936. 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));
  91937. 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));
  91938. 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));
  91939. 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));
  91940. 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));
  91941. 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));
  91942. 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));
  91943. 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));
  91944. 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));
  91945. lines.forEach(function (l) {
  91946. l.color = color;
  91947. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  91948. l.isPickable = false;
  91949. _this._lineBoundingBox.addChild(l);
  91950. });
  91951. _this._rootMesh.addChild(_this._lineBoundingBox);
  91952. // Create rotation spheres
  91953. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91954. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  91955. var _loop_1 = function (i_1) {
  91956. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  91957. sphere.rotationQuaternion = new BABYLON.Quaternion();
  91958. sphere.material = coloredMaterial;
  91959. // Drag behavior
  91960. _dragBehavior = new BABYLON.PointerDragBehavior({});
  91961. _dragBehavior.moveAttached = false;
  91962. _dragBehavior.updateDragPlane = false;
  91963. sphere.addBehavior(_dragBehavior);
  91964. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  91965. var totalTurnAmountOfDrag = 0;
  91966. _dragBehavior.onDragStartObservable.add(function (event) {
  91967. startingTurnDirection.copyFrom(sphere.forward);
  91968. totalTurnAmountOfDrag = 0;
  91969. });
  91970. _dragBehavior.onDragObservable.add(function (event) {
  91971. _this.onRotationSphereDragObservable.notifyObservers({});
  91972. if (_this.attachedMesh) {
  91973. var worldDragDirection = startingTurnDirection;
  91974. // Project the world right on to the drag plane
  91975. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  91976. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  91977. // project drag delta on to the resulting drag axis and rotate based on that
  91978. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  91979. // Make rotation relative to size of mesh.
  91980. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  91981. // Rotate based on axis
  91982. if (!_this.attachedMesh.rotationQuaternion) {
  91983. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  91984. }
  91985. if (!_this._anchorMesh.rotationQuaternion) {
  91986. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  91987. }
  91988. // Do not allow the object to turn more than a full circle
  91989. totalTurnAmountOfDrag += projectDist;
  91990. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  91991. if (i_1 >= 8) {
  91992. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  91993. }
  91994. else if (i_1 >= 4) {
  91995. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  91996. }
  91997. else {
  91998. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  91999. }
  92000. // Rotate around center of bounding box
  92001. _this._anchorMesh.addChild(_this.attachedMesh);
  92002. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  92003. _this._anchorMesh.removeChild(_this.attachedMesh);
  92004. }
  92005. _this.updateBoundingBox();
  92006. }
  92007. });
  92008. // Selection/deselection
  92009. _dragBehavior.onDragStartObservable.add(function () {
  92010. _this.onDragStartObservable.notifyObservers({});
  92011. _this._selectNode(sphere);
  92012. });
  92013. _dragBehavior.onDragEndObservable.add(function () {
  92014. _this.onRotationSphereDragEndObservable.notifyObservers({});
  92015. _this._selectNode(null);
  92016. });
  92017. this_1._rotateSpheresParent.addChild(sphere);
  92018. };
  92019. var this_1 = this, _dragBehavior;
  92020. for (var i_1 = 0; i_1 < 12; i_1++) {
  92021. _loop_1(i_1);
  92022. }
  92023. _this._rootMesh.addChild(_this._rotateSpheresParent);
  92024. // Create scale cubes
  92025. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92026. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  92027. for (var i = 0; i < 2; i++) {
  92028. for (var j = 0; j < 2; j++) {
  92029. var _loop_2 = function () {
  92030. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  92031. box.material = coloredMaterial;
  92032. // Dragging logic
  92033. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  92034. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92035. _dragBehavior.moveAttached = false;
  92036. box.addBehavior(_dragBehavior);
  92037. _dragBehavior.onDragObservable.add(function (event) {
  92038. _this.onScaleBoxDragObservable.notifyObservers({});
  92039. if (_this.attachedMesh) {
  92040. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  92041. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  92042. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  92043. _this.updateBoundingBox();
  92044. // Scale from the position of the opposite corner
  92045. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  92046. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  92047. _this._anchorMesh.addChild(_this.attachedMesh);
  92048. _this._anchorMesh.scaling.addInPlace(deltaScale);
  92049. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  92050. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  92051. }
  92052. _this._anchorMesh.removeChild(_this.attachedMesh);
  92053. }
  92054. });
  92055. // Selection/deselection
  92056. _dragBehavior.onDragStartObservable.add(function () {
  92057. _this.onDragStartObservable.notifyObservers({});
  92058. _this._selectNode(box);
  92059. });
  92060. _dragBehavior.onDragEndObservable.add(function () {
  92061. _this.onScaleBoxDragEndObservable.notifyObservers({});
  92062. _this._selectNode(null);
  92063. });
  92064. this_2._scaleBoxesParent.addChild(box);
  92065. };
  92066. var this_2 = this, _dragBehavior;
  92067. for (var k = 0; k < 2; k++) {
  92068. _loop_2();
  92069. }
  92070. }
  92071. }
  92072. _this._rootMesh.addChild(_this._scaleBoxesParent);
  92073. // Hover color change
  92074. var pointerIds = new Array();
  92075. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92076. if (!pointerIds[pointerInfo.event.pointerId]) {
  92077. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  92078. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  92079. pointerIds[pointerInfo.event.pointerId] = mesh;
  92080. mesh.material = hoverColoredMaterial;
  92081. }
  92082. });
  92083. }
  92084. else {
  92085. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  92086. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  92087. delete pointerIds[pointerInfo.event.pointerId];
  92088. }
  92089. }
  92090. });
  92091. // Update bounding box positions
  92092. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  92093. // Only update the bouding box if scaling has changed
  92094. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  92095. _this.updateBoundingBox();
  92096. }
  92097. });
  92098. _this.updateBoundingBox();
  92099. return _this;
  92100. }
  92101. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  92102. if (value) {
  92103. // Reset anchor mesh to match attached mesh's scale
  92104. // This is needed to avoid invalid box/sphere position on first drag
  92105. this._anchorMesh.addChild(value);
  92106. this._anchorMesh.removeChild(value);
  92107. this.updateBoundingBox();
  92108. }
  92109. };
  92110. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  92111. this._rotateSpheresParent.getChildMeshes()
  92112. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  92113. m.isVisible = (!selectedMesh || m == selectedMesh);
  92114. });
  92115. };
  92116. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  92117. var _this = this;
  92118. mesh.computeWorldMatrix(true);
  92119. if (!this.ignoreChildren) {
  92120. mesh.getChildMeshes().forEach(function (m) {
  92121. _this._recurseComputeWorld(m);
  92122. });
  92123. }
  92124. };
  92125. /**
  92126. * Updates the bounding box information for the Gizmo
  92127. */
  92128. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  92129. this._update();
  92130. if (this.attachedMesh) {
  92131. // Rotate based on axis
  92132. if (!this.attachedMesh.rotationQuaternion) {
  92133. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  92134. }
  92135. if (!this._anchorMesh.rotationQuaternion) {
  92136. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  92137. }
  92138. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  92139. // Store original position and reset mesh to origin before computing the bounding box
  92140. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  92141. this._tmpVector.copyFrom(this.attachedMesh.position);
  92142. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  92143. this.attachedMesh.position.set(0, 0, 0);
  92144. // Update bounding dimensions/positions
  92145. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren);
  92146. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  92147. // Update gizmo to match bounding box scaling and rotation
  92148. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  92149. 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);
  92150. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  92151. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  92152. this._lineBoundingBox.computeWorldMatrix();
  92153. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  92154. // restore position/rotation values
  92155. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  92156. this.attachedMesh.position.copyFrom(this._tmpVector);
  92157. this._recurseComputeWorld(this.attachedMesh);
  92158. }
  92159. // Update rotation sphere locations
  92160. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  92161. for (var i = 0; i < 3; i++) {
  92162. for (var j = 0; j < 2; j++) {
  92163. for (var k = 0; k < 2; k++) {
  92164. var index = ((i * 4) + (j * 2)) + k;
  92165. if (i == 0) {
  92166. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  92167. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92168. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  92169. }
  92170. if (i == 1) {
  92171. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  92172. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92173. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  92174. }
  92175. if (i == 2) {
  92176. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  92177. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92178. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  92179. }
  92180. if (this.fixedDragMeshScreenSize) {
  92181. this._rootMesh.computeWorldMatrix();
  92182. this._rotateSpheresParent.computeWorldMatrix();
  92183. rotateSpheres[index].computeWorldMatrix();
  92184. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  92185. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  92186. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  92187. }
  92188. else {
  92189. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  92190. }
  92191. }
  92192. }
  92193. }
  92194. // Update scale box locations
  92195. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  92196. for (var i = 0; i < 2; i++) {
  92197. for (var j = 0; j < 2; j++) {
  92198. for (var k = 0; k < 2; k++) {
  92199. var index = ((i * 4) + (j * 2)) + k;
  92200. if (scaleBoxes[index]) {
  92201. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  92202. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92203. if (this.fixedDragMeshScreenSize) {
  92204. this._rootMesh.computeWorldMatrix();
  92205. this._scaleBoxesParent.computeWorldMatrix();
  92206. scaleBoxes[index].computeWorldMatrix();
  92207. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  92208. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  92209. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  92210. }
  92211. else {
  92212. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  92213. }
  92214. }
  92215. }
  92216. }
  92217. }
  92218. if (this.attachedMesh) {
  92219. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  92220. }
  92221. };
  92222. /**
  92223. * Enables rotation on the specified axis and disables rotation on the others
  92224. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  92225. */
  92226. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  92227. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  92228. if (i < 4) {
  92229. m.setEnabled(axis.indexOf("x") != -1);
  92230. }
  92231. else if (i < 8) {
  92232. m.setEnabled(axis.indexOf("y") != -1);
  92233. }
  92234. else {
  92235. m.setEnabled(axis.indexOf("z") != -1);
  92236. }
  92237. });
  92238. };
  92239. /**
  92240. * Disposes of the gizmo
  92241. */
  92242. BoundingBoxGizmo.prototype.dispose = function () {
  92243. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92244. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  92245. this._lineBoundingBox.dispose();
  92246. this._rotateSpheresParent.dispose();
  92247. this._scaleBoxesParent.dispose();
  92248. _super.prototype.dispose.call(this);
  92249. };
  92250. /**
  92251. * 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)
  92252. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  92253. * @returns the bounding box mesh with the passed in mesh as a child
  92254. */
  92255. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  92256. var makeNotPickable = function (root) {
  92257. root.isPickable = false;
  92258. root.getChildMeshes().forEach(function (c) {
  92259. makeNotPickable(c);
  92260. });
  92261. };
  92262. makeNotPickable(mesh);
  92263. // Reset position to get boudning box from origin with no rotation
  92264. if (!mesh.rotationQuaternion) {
  92265. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  92266. }
  92267. var oldPos = mesh.position.clone();
  92268. var oldRot = mesh.rotationQuaternion.clone();
  92269. mesh.rotationQuaternion.set(0, 0, 0, 1);
  92270. mesh.position.set(0, 0, 0);
  92271. // Update bounding dimensions/positions
  92272. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  92273. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  92274. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  92275. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  92276. // Restore original positions
  92277. mesh.addChild(box);
  92278. mesh.rotationQuaternion.copyFrom(oldRot);
  92279. mesh.position.copyFrom(oldPos);
  92280. // Reverse parenting
  92281. mesh.removeChild(box);
  92282. box.addChild(mesh);
  92283. box.visibility = 0;
  92284. return box;
  92285. };
  92286. /**
  92287. * CustomMeshes are not supported by this gizmo
  92288. * @param mesh The mesh to replace the default mesh of the gizmo
  92289. */
  92290. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  92291. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  92292. };
  92293. return BoundingBoxGizmo;
  92294. }(BABYLON.Gizmo));
  92295. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  92296. })(BABYLON || (BABYLON = {}));
  92297. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  92298. var BABYLON;
  92299. (function (BABYLON) {
  92300. /**
  92301. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  92302. */
  92303. var GizmoManager = /** @class */ (function () {
  92304. /**
  92305. * Instatiates a gizmo manager
  92306. * @param scene the scene to overlay the gizmos on top of
  92307. */
  92308. function GizmoManager(scene) {
  92309. var _this = this;
  92310. this.scene = scene;
  92311. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  92312. this._pointerObserver = null;
  92313. this._attachedMesh = null;
  92314. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  92315. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  92316. /**
  92317. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  92318. */
  92319. this.attachableMeshes = null;
  92320. /**
  92321. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  92322. */
  92323. this.usePointerToAttachGizmos = true;
  92324. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  92325. // Instatiate/dispose gizmos based on pointer actions
  92326. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  92327. if (!_this.usePointerToAttachGizmos) {
  92328. return;
  92329. }
  92330. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92331. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  92332. var node = pointerInfo.pickInfo.pickedMesh;
  92333. if (_this.attachableMeshes == null) {
  92334. // Attach to the most parent node
  92335. while (node && node.parent != null) {
  92336. node = node.parent;
  92337. }
  92338. }
  92339. else {
  92340. // Attach to the parent node that is an attachableMesh
  92341. var found = false;
  92342. _this.attachableMeshes.forEach(function (mesh) {
  92343. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  92344. node = mesh;
  92345. found = true;
  92346. }
  92347. });
  92348. if (!found) {
  92349. node = null;
  92350. }
  92351. }
  92352. if (node instanceof BABYLON.AbstractMesh) {
  92353. _this.attachToMesh(node);
  92354. }
  92355. }
  92356. else {
  92357. _this.attachToMesh(null);
  92358. }
  92359. }
  92360. });
  92361. }
  92362. /**
  92363. * Attaches a set of gizmos to the specified mesh
  92364. * @param mesh The mesh the gizmo's should be attached to
  92365. */
  92366. GizmoManager.prototype.attachToMesh = function (mesh) {
  92367. if (this._attachedMesh) {
  92368. this._attachedMesh.removeBehavior(this._dragBehavior);
  92369. }
  92370. this._attachedMesh = mesh;
  92371. for (var key in this.gizmos) {
  92372. var gizmo = (this.gizmos[key]);
  92373. if (gizmo && this._gizmosEnabled[key]) {
  92374. gizmo.attachedMesh = mesh;
  92375. }
  92376. }
  92377. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  92378. this._attachedMesh.addBehavior(this._dragBehavior);
  92379. }
  92380. };
  92381. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  92382. get: function () {
  92383. return this._gizmosEnabled.positionGizmo;
  92384. },
  92385. /**
  92386. * If the position gizmo is enabled
  92387. */
  92388. set: function (value) {
  92389. if (value) {
  92390. if (!this.gizmos.positionGizmo) {
  92391. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  92392. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  92393. }
  92394. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  92395. }
  92396. else if (this.gizmos.positionGizmo) {
  92397. this.gizmos.positionGizmo.attachedMesh = null;
  92398. }
  92399. this._gizmosEnabled.positionGizmo = value;
  92400. },
  92401. enumerable: true,
  92402. configurable: true
  92403. });
  92404. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  92405. get: function () {
  92406. return this._gizmosEnabled.rotationGizmo;
  92407. },
  92408. /**
  92409. * If the rotation gizmo is enabled
  92410. */
  92411. set: function (value) {
  92412. if (value) {
  92413. if (!this.gizmos.rotationGizmo) {
  92414. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  92415. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  92416. }
  92417. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  92418. }
  92419. else if (this.gizmos.rotationGizmo) {
  92420. this.gizmos.rotationGizmo.attachedMesh = null;
  92421. }
  92422. this._gizmosEnabled.rotationGizmo = value;
  92423. },
  92424. enumerable: true,
  92425. configurable: true
  92426. });
  92427. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  92428. get: function () {
  92429. return this._gizmosEnabled.scaleGizmo;
  92430. },
  92431. /**
  92432. * If the scale gizmo is enabled
  92433. */
  92434. set: function (value) {
  92435. if (value) {
  92436. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  92437. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  92438. }
  92439. else if (this.gizmos.scaleGizmo) {
  92440. this.gizmos.scaleGizmo.attachedMesh = null;
  92441. }
  92442. this._gizmosEnabled.scaleGizmo = value;
  92443. },
  92444. enumerable: true,
  92445. configurable: true
  92446. });
  92447. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  92448. get: function () {
  92449. return this._gizmosEnabled.boundingBoxGizmo;
  92450. },
  92451. /**
  92452. * If the boundingBox gizmo is enabled
  92453. */
  92454. set: function (value) {
  92455. if (value) {
  92456. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  92457. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  92458. if (this._attachedMesh) {
  92459. this._attachedMesh.removeBehavior(this._dragBehavior);
  92460. this._attachedMesh.addBehavior(this._dragBehavior);
  92461. }
  92462. }
  92463. else if (this.gizmos.boundingBoxGizmo) {
  92464. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  92465. }
  92466. this._gizmosEnabled.boundingBoxGizmo = value;
  92467. },
  92468. enumerable: true,
  92469. configurable: true
  92470. });
  92471. /**
  92472. * Disposes of the gizmo manager
  92473. */
  92474. GizmoManager.prototype.dispose = function () {
  92475. this.scene.onPointerObservable.remove(this._pointerObserver);
  92476. for (var key in this.gizmos) {
  92477. var gizmo = (this.gizmos[key]);
  92478. if (gizmo) {
  92479. gizmo.dispose();
  92480. }
  92481. }
  92482. this._dragBehavior.detach();
  92483. };
  92484. return GizmoManager;
  92485. }());
  92486. BABYLON.GizmoManager = GizmoManager;
  92487. })(BABYLON || (BABYLON = {}));
  92488. //# sourceMappingURL=babylon.gizmoManager.js.map
  92489. var BABYLON;
  92490. (function (BABYLON) {
  92491. /**
  92492. * Defines a target to use with MorphTargetManager
  92493. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  92494. */
  92495. var MorphTarget = /** @class */ (function () {
  92496. /**
  92497. * Creates a new MorphTarget
  92498. * @param name defines the name of the target
  92499. * @param influence defines the influence to use
  92500. */
  92501. function MorphTarget(
  92502. /** defines the name of the target */
  92503. name, influence, scene) {
  92504. if (influence === void 0) { influence = 0; }
  92505. if (scene === void 0) { scene = null; }
  92506. this.name = name;
  92507. /**
  92508. * Gets or sets the list of animations
  92509. */
  92510. this.animations = new Array();
  92511. this._positions = null;
  92512. this._normals = null;
  92513. this._tangents = null;
  92514. /**
  92515. * Observable raised when the influence changes
  92516. */
  92517. this.onInfluenceChanged = new BABYLON.Observable();
  92518. this._animationPropertiesOverride = null;
  92519. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92520. this.influence = influence;
  92521. }
  92522. Object.defineProperty(MorphTarget.prototype, "influence", {
  92523. /**
  92524. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  92525. */
  92526. get: function () {
  92527. return this._influence;
  92528. },
  92529. set: function (influence) {
  92530. if (this._influence === influence) {
  92531. return;
  92532. }
  92533. var previous = this._influence;
  92534. this._influence = influence;
  92535. if (this.onInfluenceChanged.hasObservers) {
  92536. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  92537. }
  92538. },
  92539. enumerable: true,
  92540. configurable: true
  92541. });
  92542. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  92543. /**
  92544. * Gets or sets the animation properties override
  92545. */
  92546. get: function () {
  92547. if (!this._animationPropertiesOverride && this._scene) {
  92548. return this._scene.animationPropertiesOverride;
  92549. }
  92550. return this._animationPropertiesOverride;
  92551. },
  92552. set: function (value) {
  92553. this._animationPropertiesOverride = value;
  92554. },
  92555. enumerable: true,
  92556. configurable: true
  92557. });
  92558. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  92559. /**
  92560. * Gets a boolean defining if the target contains position data
  92561. */
  92562. get: function () {
  92563. return !!this._positions;
  92564. },
  92565. enumerable: true,
  92566. configurable: true
  92567. });
  92568. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  92569. /**
  92570. * Gets a boolean defining if the target contains normal data
  92571. */
  92572. get: function () {
  92573. return !!this._normals;
  92574. },
  92575. enumerable: true,
  92576. configurable: true
  92577. });
  92578. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  92579. /**
  92580. * Gets a boolean defining if the target contains tangent data
  92581. */
  92582. get: function () {
  92583. return !!this._tangents;
  92584. },
  92585. enumerable: true,
  92586. configurable: true
  92587. });
  92588. /**
  92589. * Affects position data to this target
  92590. * @param data defines the position data to use
  92591. */
  92592. MorphTarget.prototype.setPositions = function (data) {
  92593. this._positions = data;
  92594. };
  92595. /**
  92596. * Gets the position data stored in this target
  92597. * @returns a FloatArray containing the position data (or null if not present)
  92598. */
  92599. MorphTarget.prototype.getPositions = function () {
  92600. return this._positions;
  92601. };
  92602. /**
  92603. * Affects normal data to this target
  92604. * @param data defines the normal data to use
  92605. */
  92606. MorphTarget.prototype.setNormals = function (data) {
  92607. this._normals = data;
  92608. };
  92609. /**
  92610. * Gets the normal data stored in this target
  92611. * @returns a FloatArray containing the normal data (or null if not present)
  92612. */
  92613. MorphTarget.prototype.getNormals = function () {
  92614. return this._normals;
  92615. };
  92616. /**
  92617. * Affects tangent data to this target
  92618. * @param data defines the tangent data to use
  92619. */
  92620. MorphTarget.prototype.setTangents = function (data) {
  92621. this._tangents = data;
  92622. };
  92623. /**
  92624. * Gets the tangent data stored in this target
  92625. * @returns a FloatArray containing the tangent data (or null if not present)
  92626. */
  92627. MorphTarget.prototype.getTangents = function () {
  92628. return this._tangents;
  92629. };
  92630. /**
  92631. * Serializes the current target into a Serialization object
  92632. * @returns the serialized object
  92633. */
  92634. MorphTarget.prototype.serialize = function () {
  92635. var serializationObject = {};
  92636. serializationObject.name = this.name;
  92637. serializationObject.influence = this.influence;
  92638. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  92639. if (this.hasNormals) {
  92640. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  92641. }
  92642. if (this.hasTangents) {
  92643. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  92644. }
  92645. // Animations
  92646. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  92647. return serializationObject;
  92648. };
  92649. // Statics
  92650. /**
  92651. * Creates a new target from serialized data
  92652. * @param serializationObject defines the serialized data to use
  92653. * @returns a new MorphTarget
  92654. */
  92655. MorphTarget.Parse = function (serializationObject) {
  92656. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  92657. result.setPositions(serializationObject.positions);
  92658. if (serializationObject.normals) {
  92659. result.setNormals(serializationObject.normals);
  92660. }
  92661. if (serializationObject.tangents) {
  92662. result.setTangents(serializationObject.tangents);
  92663. }
  92664. // Animations
  92665. if (serializationObject.animations) {
  92666. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  92667. var parsedAnimation = serializationObject.animations[animationIndex];
  92668. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  92669. }
  92670. }
  92671. return result;
  92672. };
  92673. /**
  92674. * Creates a MorphTarget from mesh data
  92675. * @param mesh defines the source mesh
  92676. * @param name defines the name to use for the new target
  92677. * @param influence defines the influence to attach to the target
  92678. * @returns a new MorphTarget
  92679. */
  92680. MorphTarget.FromMesh = function (mesh, name, influence) {
  92681. if (!name) {
  92682. name = mesh.name;
  92683. }
  92684. var result = new MorphTarget(name, influence, mesh.getScene());
  92685. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  92686. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  92687. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  92688. }
  92689. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  92690. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  92691. }
  92692. return result;
  92693. };
  92694. return MorphTarget;
  92695. }());
  92696. BABYLON.MorphTarget = MorphTarget;
  92697. })(BABYLON || (BABYLON = {}));
  92698. //# sourceMappingURL=babylon.morphTarget.js.map
  92699. var BABYLON;
  92700. (function (BABYLON) {
  92701. /**
  92702. * This class is used to deform meshes using morphing between different targets
  92703. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  92704. */
  92705. var MorphTargetManager = /** @class */ (function () {
  92706. /**
  92707. * Creates a new MorphTargetManager
  92708. * @param scene defines the current scene
  92709. */
  92710. function MorphTargetManager(scene) {
  92711. if (scene === void 0) { scene = null; }
  92712. this._targets = new Array();
  92713. this._targetObservable = new Array();
  92714. this._activeTargets = new BABYLON.SmartArray(16);
  92715. this._supportsNormals = false;
  92716. this._supportsTangents = false;
  92717. this._vertexCount = 0;
  92718. this._uniqueId = 0;
  92719. this._tempInfluences = new Array();
  92720. if (!scene) {
  92721. scene = BABYLON.Engine.LastCreatedScene;
  92722. }
  92723. this._scene = scene;
  92724. if (this._scene) {
  92725. this._scene.morphTargetManagers.push(this);
  92726. this._uniqueId = this._scene.getUniqueId();
  92727. }
  92728. }
  92729. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  92730. /**
  92731. * Gets the unique ID of this manager
  92732. */
  92733. get: function () {
  92734. return this._uniqueId;
  92735. },
  92736. enumerable: true,
  92737. configurable: true
  92738. });
  92739. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  92740. /**
  92741. * Gets the number of vertices handled by this manager
  92742. */
  92743. get: function () {
  92744. return this._vertexCount;
  92745. },
  92746. enumerable: true,
  92747. configurable: true
  92748. });
  92749. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  92750. /**
  92751. * Gets a boolean indicating if this manager supports morphing of normals
  92752. */
  92753. get: function () {
  92754. return this._supportsNormals;
  92755. },
  92756. enumerable: true,
  92757. configurable: true
  92758. });
  92759. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  92760. /**
  92761. * Gets a boolean indicating if this manager supports morphing of tangents
  92762. */
  92763. get: function () {
  92764. return this._supportsTangents;
  92765. },
  92766. enumerable: true,
  92767. configurable: true
  92768. });
  92769. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  92770. /**
  92771. * Gets the number of targets stored in this manager
  92772. */
  92773. get: function () {
  92774. return this._targets.length;
  92775. },
  92776. enumerable: true,
  92777. configurable: true
  92778. });
  92779. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  92780. /**
  92781. * Gets the number of influencers (ie. the number of targets with influences > 0)
  92782. */
  92783. get: function () {
  92784. return this._activeTargets.length;
  92785. },
  92786. enumerable: true,
  92787. configurable: true
  92788. });
  92789. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  92790. /**
  92791. * Gets the list of influences (one per target)
  92792. */
  92793. get: function () {
  92794. return this._influences;
  92795. },
  92796. enumerable: true,
  92797. configurable: true
  92798. });
  92799. /**
  92800. * Gets the active target at specified index. An active target is a target with an influence > 0
  92801. * @param index defines the index to check
  92802. * @returns the requested target
  92803. */
  92804. MorphTargetManager.prototype.getActiveTarget = function (index) {
  92805. return this._activeTargets.data[index];
  92806. };
  92807. /**
  92808. * Gets the target at specified index
  92809. * @param index defines the index to check
  92810. * @returns the requested target
  92811. */
  92812. MorphTargetManager.prototype.getTarget = function (index) {
  92813. return this._targets[index];
  92814. };
  92815. /**
  92816. * Add a new target to this manager
  92817. * @param target defines the target to add
  92818. */
  92819. MorphTargetManager.prototype.addTarget = function (target) {
  92820. var _this = this;
  92821. this._targets.push(target);
  92822. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  92823. _this._syncActiveTargets(needUpdate);
  92824. }));
  92825. this._syncActiveTargets(true);
  92826. };
  92827. /**
  92828. * Removes a target from the manager
  92829. * @param target defines the target to remove
  92830. */
  92831. MorphTargetManager.prototype.removeTarget = function (target) {
  92832. var index = this._targets.indexOf(target);
  92833. if (index >= 0) {
  92834. this._targets.splice(index, 1);
  92835. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  92836. this._syncActiveTargets(true);
  92837. }
  92838. };
  92839. /**
  92840. * Serializes the current manager into a Serialization object
  92841. * @returns the serialized object
  92842. */
  92843. MorphTargetManager.prototype.serialize = function () {
  92844. var serializationObject = {};
  92845. serializationObject.id = this.uniqueId;
  92846. serializationObject.targets = [];
  92847. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  92848. var target = _a[_i];
  92849. serializationObject.targets.push(target.serialize());
  92850. }
  92851. return serializationObject;
  92852. };
  92853. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  92854. var influenceCount = 0;
  92855. this._activeTargets.reset();
  92856. this._supportsNormals = true;
  92857. this._supportsTangents = true;
  92858. this._vertexCount = 0;
  92859. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  92860. var target = _a[_i];
  92861. this._activeTargets.push(target);
  92862. this._tempInfluences[influenceCount++] = target.influence;
  92863. var positions = target.getPositions();
  92864. if (positions) {
  92865. this._supportsNormals = this._supportsNormals && target.hasNormals;
  92866. this._supportsTangents = this._supportsTangents && target.hasTangents;
  92867. var vertexCount = positions.length / 3;
  92868. if (this._vertexCount === 0) {
  92869. this._vertexCount = vertexCount;
  92870. }
  92871. else if (this._vertexCount !== vertexCount) {
  92872. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  92873. return;
  92874. }
  92875. }
  92876. }
  92877. if (!this._influences || this._influences.length !== influenceCount) {
  92878. this._influences = new Float32Array(influenceCount);
  92879. }
  92880. for (var index = 0; index < influenceCount; index++) {
  92881. this._influences[index] = this._tempInfluences[index];
  92882. }
  92883. if (needUpdate) {
  92884. this.synchronize();
  92885. }
  92886. };
  92887. /**
  92888. * Syncrhonize the targets with all the meshes using this morph target manager
  92889. */
  92890. MorphTargetManager.prototype.synchronize = function () {
  92891. if (!this._scene) {
  92892. return;
  92893. }
  92894. // Flag meshes as dirty to resync with the active targets
  92895. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  92896. var mesh = _a[_i];
  92897. if (mesh.morphTargetManager === this) {
  92898. mesh._syncGeometryWithMorphTargetManager();
  92899. }
  92900. }
  92901. };
  92902. // Statics
  92903. /**
  92904. * Creates a new MorphTargetManager from serialized data
  92905. * @param serializationObject defines the serialized data
  92906. * @param scene defines the hosting scene
  92907. * @returns the new MorphTargetManager
  92908. */
  92909. MorphTargetManager.Parse = function (serializationObject, scene) {
  92910. var result = new MorphTargetManager(scene);
  92911. result._uniqueId = serializationObject.id;
  92912. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  92913. var targetData = _a[_i];
  92914. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  92915. }
  92916. return result;
  92917. };
  92918. return MorphTargetManager;
  92919. }());
  92920. BABYLON.MorphTargetManager = MorphTargetManager;
  92921. })(BABYLON || (BABYLON = {}));
  92922. //# sourceMappingURL=babylon.morphTargetManager.js.map
  92923. var BABYLON;
  92924. (function (BABYLON) {
  92925. var Octree = /** @class */ (function () {
  92926. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  92927. if (maxDepth === void 0) { maxDepth = 2; }
  92928. this.maxDepth = maxDepth;
  92929. this.dynamicContent = new Array();
  92930. this._maxBlockCapacity = maxBlockCapacity || 64;
  92931. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  92932. this._creationFunc = creationFunc;
  92933. }
  92934. // Methods
  92935. Octree.prototype.update = function (worldMin, worldMax, entries) {
  92936. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  92937. };
  92938. Octree.prototype.addMesh = function (entry) {
  92939. for (var index = 0; index < this.blocks.length; index++) {
  92940. var block = this.blocks[index];
  92941. block.addEntry(entry);
  92942. }
  92943. };
  92944. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  92945. this._selectionContent.reset();
  92946. for (var index = 0; index < this.blocks.length; index++) {
  92947. var block = this.blocks[index];
  92948. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  92949. }
  92950. if (allowDuplicate) {
  92951. this._selectionContent.concat(this.dynamicContent);
  92952. }
  92953. else {
  92954. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92955. }
  92956. return this._selectionContent;
  92957. };
  92958. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  92959. this._selectionContent.reset();
  92960. for (var index = 0; index < this.blocks.length; index++) {
  92961. var block = this.blocks[index];
  92962. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  92963. }
  92964. if (allowDuplicate) {
  92965. this._selectionContent.concat(this.dynamicContent);
  92966. }
  92967. else {
  92968. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92969. }
  92970. return this._selectionContent;
  92971. };
  92972. Octree.prototype.intersectsRay = function (ray) {
  92973. this._selectionContent.reset();
  92974. for (var index = 0; index < this.blocks.length; index++) {
  92975. var block = this.blocks[index];
  92976. block.intersectsRay(ray, this._selectionContent);
  92977. }
  92978. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  92979. return this._selectionContent;
  92980. };
  92981. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  92982. target.blocks = new Array();
  92983. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  92984. // Segmenting space
  92985. for (var x = 0; x < 2; x++) {
  92986. for (var y = 0; y < 2; y++) {
  92987. for (var z = 0; z < 2; z++) {
  92988. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  92989. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  92990. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  92991. block.addEntries(entries);
  92992. target.blocks.push(block);
  92993. }
  92994. }
  92995. }
  92996. };
  92997. Octree.CreationFuncForMeshes = function (entry, block) {
  92998. var boundingInfo = entry.getBoundingInfo();
  92999. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  93000. block.entries.push(entry);
  93001. }
  93002. };
  93003. Octree.CreationFuncForSubMeshes = function (entry, block) {
  93004. var boundingInfo = entry.getBoundingInfo();
  93005. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  93006. block.entries.push(entry);
  93007. }
  93008. };
  93009. return Octree;
  93010. }());
  93011. BABYLON.Octree = Octree;
  93012. })(BABYLON || (BABYLON = {}));
  93013. //# sourceMappingURL=babylon.octree.js.map
  93014. var BABYLON;
  93015. (function (BABYLON) {
  93016. var OctreeBlock = /** @class */ (function () {
  93017. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  93018. this.entries = new Array();
  93019. this._boundingVectors = new Array();
  93020. this._capacity = capacity;
  93021. this._depth = depth;
  93022. this._maxDepth = maxDepth;
  93023. this._creationFunc = creationFunc;
  93024. this._minPoint = minPoint;
  93025. this._maxPoint = maxPoint;
  93026. this._boundingVectors.push(minPoint.clone());
  93027. this._boundingVectors.push(maxPoint.clone());
  93028. this._boundingVectors.push(minPoint.clone());
  93029. this._boundingVectors[2].x = maxPoint.x;
  93030. this._boundingVectors.push(minPoint.clone());
  93031. this._boundingVectors[3].y = maxPoint.y;
  93032. this._boundingVectors.push(minPoint.clone());
  93033. this._boundingVectors[4].z = maxPoint.z;
  93034. this._boundingVectors.push(maxPoint.clone());
  93035. this._boundingVectors[5].z = minPoint.z;
  93036. this._boundingVectors.push(maxPoint.clone());
  93037. this._boundingVectors[6].x = minPoint.x;
  93038. this._boundingVectors.push(maxPoint.clone());
  93039. this._boundingVectors[7].y = minPoint.y;
  93040. }
  93041. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  93042. // Property
  93043. get: function () {
  93044. return this._capacity;
  93045. },
  93046. enumerable: true,
  93047. configurable: true
  93048. });
  93049. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  93050. get: function () {
  93051. return this._minPoint;
  93052. },
  93053. enumerable: true,
  93054. configurable: true
  93055. });
  93056. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  93057. get: function () {
  93058. return this._maxPoint;
  93059. },
  93060. enumerable: true,
  93061. configurable: true
  93062. });
  93063. // Methods
  93064. OctreeBlock.prototype.addEntry = function (entry) {
  93065. if (this.blocks) {
  93066. for (var index = 0; index < this.blocks.length; index++) {
  93067. var block = this.blocks[index];
  93068. block.addEntry(entry);
  93069. }
  93070. return;
  93071. }
  93072. this._creationFunc(entry, this);
  93073. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  93074. this.createInnerBlocks();
  93075. }
  93076. };
  93077. OctreeBlock.prototype.addEntries = function (entries) {
  93078. for (var index = 0; index < entries.length; index++) {
  93079. var mesh = entries[index];
  93080. this.addEntry(mesh);
  93081. }
  93082. };
  93083. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  93084. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  93085. if (this.blocks) {
  93086. for (var index = 0; index < this.blocks.length; index++) {
  93087. var block = this.blocks[index];
  93088. block.select(frustumPlanes, selection, allowDuplicate);
  93089. }
  93090. return;
  93091. }
  93092. if (allowDuplicate) {
  93093. selection.concat(this.entries);
  93094. }
  93095. else {
  93096. selection.concatWithNoDuplicate(this.entries);
  93097. }
  93098. }
  93099. };
  93100. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  93101. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  93102. if (this.blocks) {
  93103. for (var index = 0; index < this.blocks.length; index++) {
  93104. var block = this.blocks[index];
  93105. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  93106. }
  93107. return;
  93108. }
  93109. if (allowDuplicate) {
  93110. selection.concat(this.entries);
  93111. }
  93112. else {
  93113. selection.concatWithNoDuplicate(this.entries);
  93114. }
  93115. }
  93116. };
  93117. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  93118. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  93119. if (this.blocks) {
  93120. for (var index = 0; index < this.blocks.length; index++) {
  93121. var block = this.blocks[index];
  93122. block.intersectsRay(ray, selection);
  93123. }
  93124. return;
  93125. }
  93126. selection.concatWithNoDuplicate(this.entries);
  93127. }
  93128. };
  93129. OctreeBlock.prototype.createInnerBlocks = function () {
  93130. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  93131. };
  93132. return OctreeBlock;
  93133. }());
  93134. BABYLON.OctreeBlock = OctreeBlock;
  93135. })(BABYLON || (BABYLON = {}));
  93136. //# sourceMappingURL=babylon.octreeBlock.js.map
  93137. var BABYLON;
  93138. (function (BABYLON) {
  93139. /**
  93140. * Postprocess used to generate anaglyphic rendering
  93141. */
  93142. var AnaglyphPostProcess = /** @class */ (function (_super) {
  93143. __extends(AnaglyphPostProcess, _super);
  93144. /**
  93145. * Creates a new AnaglyphPostProcess
  93146. * @param name defines postprocess name
  93147. * @param options defines creation options or target ratio scale
  93148. * @param rigCameras defines cameras using this postprocess
  93149. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  93150. * @param engine defines hosting engine
  93151. * @param reusable defines if the postprocess will be reused multiple times per frame
  93152. */
  93153. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  93154. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  93155. _this._passedProcess = rigCameras[0]._rigPostProcess;
  93156. _this.onApplyObservable.add(function (effect) {
  93157. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  93158. });
  93159. return _this;
  93160. }
  93161. return AnaglyphPostProcess;
  93162. }(BABYLON.PostProcess));
  93163. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  93164. })(BABYLON || (BABYLON = {}));
  93165. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  93166. var BABYLON;
  93167. (function (BABYLON) {
  93168. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  93169. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93170. });
  93171. /**
  93172. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  93173. */
  93174. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  93175. __extends(AnaglyphArcRotateCamera, _super);
  93176. /**
  93177. * Creates a new AnaglyphArcRotateCamera
  93178. * @param name defines camera name
  93179. * @param alpha defines alpha angle (in radians)
  93180. * @param beta defines beta angle (in radians)
  93181. * @param radius defines radius
  93182. * @param target defines camera target
  93183. * @param interaxialDistance defines distance between each color axis
  93184. * @param scene defines the hosting scene
  93185. */
  93186. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  93187. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93188. _this.interaxialDistance = interaxialDistance;
  93189. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93190. return _this;
  93191. }
  93192. /**
  93193. * Gets camera class name
  93194. * @returns AnaglyphArcRotateCamera
  93195. */
  93196. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  93197. return "AnaglyphArcRotateCamera";
  93198. };
  93199. return AnaglyphArcRotateCamera;
  93200. }(BABYLON.ArcRotateCamera));
  93201. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  93202. })(BABYLON || (BABYLON = {}));
  93203. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  93204. var BABYLON;
  93205. (function (BABYLON) {
  93206. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  93207. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93208. });
  93209. /**
  93210. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  93211. */
  93212. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  93213. __extends(AnaglyphFreeCamera, _super);
  93214. /**
  93215. * Creates a new AnaglyphFreeCamera
  93216. * @param name defines camera name
  93217. * @param position defines initial position
  93218. * @param interaxialDistance defines distance between each color axis
  93219. * @param scene defines the hosting scene
  93220. */
  93221. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  93222. var _this = _super.call(this, name, position, scene) || this;
  93223. _this.interaxialDistance = interaxialDistance;
  93224. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93225. return _this;
  93226. }
  93227. /**
  93228. * Gets camera class name
  93229. * @returns AnaglyphFreeCamera
  93230. */
  93231. AnaglyphFreeCamera.prototype.getClassName = function () {
  93232. return "AnaglyphFreeCamera";
  93233. };
  93234. return AnaglyphFreeCamera;
  93235. }(BABYLON.FreeCamera));
  93236. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  93237. })(BABYLON || (BABYLON = {}));
  93238. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  93239. var BABYLON;
  93240. (function (BABYLON) {
  93241. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  93242. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93243. });
  93244. /**
  93245. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  93246. */
  93247. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  93248. __extends(AnaglyphGamepadCamera, _super);
  93249. /**
  93250. * Creates a new AnaglyphGamepadCamera
  93251. * @param name defines camera name
  93252. * @param position defines initial position
  93253. * @param interaxialDistance defines distance between each color axis
  93254. * @param scene defines the hosting scene
  93255. */
  93256. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  93257. var _this = _super.call(this, name, position, scene) || this;
  93258. _this.interaxialDistance = interaxialDistance;
  93259. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93260. return _this;
  93261. }
  93262. /**
  93263. * Gets camera class name
  93264. * @returns AnaglyphGamepadCamera
  93265. */
  93266. AnaglyphGamepadCamera.prototype.getClassName = function () {
  93267. return "AnaglyphGamepadCamera";
  93268. };
  93269. return AnaglyphGamepadCamera;
  93270. }(BABYLON.GamepadCamera));
  93271. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  93272. })(BABYLON || (BABYLON = {}));
  93273. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  93274. var BABYLON;
  93275. (function (BABYLON) {
  93276. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  93277. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93278. });
  93279. /**
  93280. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  93281. */
  93282. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  93283. __extends(AnaglyphUniversalCamera, _super);
  93284. /**
  93285. * Creates a new AnaglyphUniversalCamera
  93286. * @param name defines camera name
  93287. * @param position defines initial position
  93288. * @param interaxialDistance defines distance between each color axis
  93289. * @param scene defines the hosting scene
  93290. */
  93291. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  93292. var _this = _super.call(this, name, position, scene) || this;
  93293. _this.interaxialDistance = interaxialDistance;
  93294. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93295. return _this;
  93296. }
  93297. /**
  93298. * Gets camera class name
  93299. * @returns AnaglyphUniversalCamera
  93300. */
  93301. AnaglyphUniversalCamera.prototype.getClassName = function () {
  93302. return "AnaglyphUniversalCamera";
  93303. };
  93304. return AnaglyphUniversalCamera;
  93305. }(BABYLON.UniversalCamera));
  93306. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  93307. })(BABYLON || (BABYLON = {}));
  93308. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  93309. var BABYLON;
  93310. (function (BABYLON) {
  93311. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  93312. __extends(StereoscopicInterlacePostProcess, _super);
  93313. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  93314. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  93315. _this._passedProcess = rigCameras[0]._rigPostProcess;
  93316. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  93317. _this.onSizeChangedObservable.add(function () {
  93318. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  93319. });
  93320. _this.onApplyObservable.add(function (effect) {
  93321. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  93322. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  93323. });
  93324. return _this;
  93325. }
  93326. return StereoscopicInterlacePostProcess;
  93327. }(BABYLON.PostProcess));
  93328. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  93329. })(BABYLON || (BABYLON = {}));
  93330. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  93331. var BABYLON;
  93332. (function (BABYLON) {
  93333. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  93334. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  93335. });
  93336. /**
  93337. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  93338. */
  93339. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  93340. __extends(StereoscopicArcRotateCamera, _super);
  93341. /**
  93342. * Creates a new StereoscopicArcRotateCamera
  93343. * @param name defines camera name
  93344. * @param alpha defines alpha angle (in radians)
  93345. * @param beta defines beta angle (in radians)
  93346. * @param radius defines radius
  93347. * @param target defines camera target
  93348. * @param interaxialDistance defines distance between each color axis
  93349. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  93350. * @param scene defines the hosting scene
  93351. */
  93352. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  93353. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93354. _this.interaxialDistance = interaxialDistance;
  93355. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  93356. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  93357. return _this;
  93358. }
  93359. /**
  93360. * Gets camera class name
  93361. * @returns StereoscopicArcRotateCamera
  93362. */
  93363. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  93364. return "StereoscopicArcRotateCamera";
  93365. };
  93366. return StereoscopicArcRotateCamera;
  93367. }(BABYLON.ArcRotateCamera));
  93368. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  93369. })(BABYLON || (BABYLON = {}));
  93370. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  93371. var BABYLON;
  93372. (function (BABYLON) {
  93373. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  93374. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  93375. });
  93376. /**
  93377. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  93378. */
  93379. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  93380. __extends(StereoscopicFreeCamera, _super);
  93381. /**
  93382. * Creates a new StereoscopicFreeCamera
  93383. * @param name defines camera name
  93384. * @param position defines initial position
  93385. * @param interaxialDistance defines distance between each color axis
  93386. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  93387. * @param scene defines the hosting scene
  93388. */
  93389. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  93390. var _this = _super.call(this, name, position, scene) || this;
  93391. _this.interaxialDistance = interaxialDistance;
  93392. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  93393. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  93394. return _this;
  93395. }
  93396. /**
  93397. * Gets camera class name
  93398. * @returns StereoscopicFreeCamera
  93399. */
  93400. StereoscopicFreeCamera.prototype.getClassName = function () {
  93401. return "StereoscopicFreeCamera";
  93402. };
  93403. return StereoscopicFreeCamera;
  93404. }(BABYLON.FreeCamera));
  93405. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  93406. })(BABYLON || (BABYLON = {}));
  93407. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  93408. var BABYLON;
  93409. (function (BABYLON) {
  93410. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  93411. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  93412. });
  93413. /**
  93414. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  93415. */
  93416. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  93417. __extends(StereoscopicGamepadCamera, _super);
  93418. /**
  93419. * Creates a new StereoscopicGamepadCamera
  93420. * @param name defines camera name
  93421. * @param position defines initial position
  93422. * @param interaxialDistance defines distance between each color axis
  93423. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  93424. * @param scene defines the hosting scene
  93425. */
  93426. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  93427. var _this = _super.call(this, name, position, scene) || this;
  93428. _this.interaxialDistance = interaxialDistance;
  93429. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  93430. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  93431. return _this;
  93432. }
  93433. /**
  93434. * Gets camera class name
  93435. * @returns StereoscopicGamepadCamera
  93436. */
  93437. StereoscopicGamepadCamera.prototype.getClassName = function () {
  93438. return "StereoscopicGamepadCamera";
  93439. };
  93440. return StereoscopicGamepadCamera;
  93441. }(BABYLON.GamepadCamera));
  93442. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  93443. })(BABYLON || (BABYLON = {}));
  93444. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  93445. var BABYLON;
  93446. (function (BABYLON) {
  93447. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  93448. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  93449. });
  93450. /**
  93451. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  93452. */
  93453. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  93454. __extends(StereoscopicUniversalCamera, _super);
  93455. /**
  93456. * Creates a new StereoscopicUniversalCamera
  93457. * @param name defines camera name
  93458. * @param position defines initial position
  93459. * @param interaxialDistance defines distance between each color axis
  93460. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  93461. * @param scene defines the hosting scene
  93462. */
  93463. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  93464. var _this = _super.call(this, name, position, scene) || this;
  93465. _this.interaxialDistance = interaxialDistance;
  93466. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  93467. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  93468. return _this;
  93469. }
  93470. /**
  93471. * Gets camera class name
  93472. * @returns StereoscopicUniversalCamera
  93473. */
  93474. StereoscopicUniversalCamera.prototype.getClassName = function () {
  93475. return "StereoscopicUniversalCamera";
  93476. };
  93477. return StereoscopicUniversalCamera;
  93478. }(BABYLON.UniversalCamera));
  93479. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  93480. })(BABYLON || (BABYLON = {}));
  93481. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  93482. var BABYLON;
  93483. (function (BABYLON) {
  93484. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  93485. __extends(VRDistortionCorrectionPostProcess, _super);
  93486. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  93487. var _this = _super.call(this, name, "vrDistortionCorrection", [
  93488. 'LensCenter',
  93489. 'Scale',
  93490. 'ScaleIn',
  93491. 'HmdWarpParam'
  93492. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  93493. _this._isRightEye = isRightEye;
  93494. _this._distortionFactors = vrMetrics.distortionK;
  93495. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  93496. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  93497. _this.adaptScaleToCurrentViewport = true;
  93498. _this.onSizeChangedObservable.add(function () {
  93499. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  93500. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  93501. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  93502. });
  93503. _this.onApplyObservable.add(function (effect) {
  93504. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  93505. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  93506. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  93507. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  93508. });
  93509. return _this;
  93510. }
  93511. return VRDistortionCorrectionPostProcess;
  93512. }(BABYLON.PostProcess));
  93513. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  93514. })(BABYLON || (BABYLON = {}));
  93515. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  93516. var BABYLON;
  93517. (function (BABYLON) {
  93518. /**
  93519. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  93520. * Screen rotation is taken into account.
  93521. */
  93522. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  93523. function FreeCameraDeviceOrientationInput() {
  93524. var _this = this;
  93525. this._screenOrientationAngle = 0;
  93526. this._screenQuaternion = new BABYLON.Quaternion();
  93527. this._alpha = 0;
  93528. this._beta = 0;
  93529. this._gamma = 0;
  93530. this._orientationChanged = function () {
  93531. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  93532. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  93533. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  93534. };
  93535. this._deviceOrientation = function (evt) {
  93536. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  93537. _this._beta = evt.beta !== null ? evt.beta : 0;
  93538. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  93539. };
  93540. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  93541. this._orientationChanged();
  93542. }
  93543. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  93544. get: function () {
  93545. return this._camera;
  93546. },
  93547. set: function (camera) {
  93548. this._camera = camera;
  93549. if (this._camera != null && !this._camera.rotationQuaternion) {
  93550. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  93551. }
  93552. },
  93553. enumerable: true,
  93554. configurable: true
  93555. });
  93556. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  93557. window.addEventListener("orientationchange", this._orientationChanged);
  93558. window.addEventListener("deviceorientation", this._deviceOrientation);
  93559. //In certain cases, the attach control is called AFTER orientation was changed,
  93560. //So this is needed.
  93561. this._orientationChanged();
  93562. };
  93563. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  93564. window.removeEventListener("orientationchange", this._orientationChanged);
  93565. window.removeEventListener("deviceorientation", this._deviceOrientation);
  93566. };
  93567. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  93568. //if no device orientation provided, don't update the rotation.
  93569. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  93570. if (!this._alpha)
  93571. return;
  93572. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  93573. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  93574. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  93575. //Mirror on XY Plane
  93576. this._camera.rotationQuaternion.z *= -1;
  93577. this._camera.rotationQuaternion.w *= -1;
  93578. };
  93579. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  93580. return "FreeCameraDeviceOrientationInput";
  93581. };
  93582. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  93583. return "deviceOrientation";
  93584. };
  93585. return FreeCameraDeviceOrientationInput;
  93586. }());
  93587. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  93588. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  93589. })(BABYLON || (BABYLON = {}));
  93590. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  93591. var BABYLON;
  93592. (function (BABYLON) {
  93593. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  93594. function ArcRotateCameraVRDeviceOrientationInput() {
  93595. this.alphaCorrection = 1;
  93596. this.betaCorrection = 1;
  93597. this.gammaCorrection = 1;
  93598. this._alpha = 0;
  93599. this._gamma = 0;
  93600. this._dirty = false;
  93601. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  93602. }
  93603. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  93604. this.camera.attachControl(element, noPreventDefault);
  93605. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  93606. };
  93607. /** @hidden */
  93608. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  93609. if (evt.alpha !== null) {
  93610. this._alpha = +evt.alpha | 0;
  93611. }
  93612. if (evt.gamma !== null) {
  93613. this._gamma = +evt.gamma | 0;
  93614. }
  93615. this._dirty = true;
  93616. };
  93617. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  93618. if (this._dirty) {
  93619. this._dirty = false;
  93620. if (this._gamma < 0) {
  93621. this._gamma = 180 + this._gamma;
  93622. }
  93623. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  93624. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  93625. }
  93626. };
  93627. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  93628. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  93629. };
  93630. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  93631. return "ArcRotateCameraVRDeviceOrientationInput";
  93632. };
  93633. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  93634. return "VRDeviceOrientation";
  93635. };
  93636. return ArcRotateCameraVRDeviceOrientationInput;
  93637. }());
  93638. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  93639. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  93640. })(BABYLON || (BABYLON = {}));
  93641. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  93642. var BABYLON;
  93643. (function (BABYLON) {
  93644. var VRCameraMetrics = /** @class */ (function () {
  93645. function VRCameraMetrics() {
  93646. this.compensateDistortion = true;
  93647. }
  93648. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  93649. get: function () {
  93650. return this.hResolution / (2 * this.vResolution);
  93651. },
  93652. enumerable: true,
  93653. configurable: true
  93654. });
  93655. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  93656. get: function () {
  93657. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  93658. },
  93659. enumerable: true,
  93660. configurable: true
  93661. });
  93662. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  93663. get: function () {
  93664. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  93665. var h = (4 * meters) / this.hScreenSize;
  93666. return BABYLON.Matrix.Translation(h, 0, 0);
  93667. },
  93668. enumerable: true,
  93669. configurable: true
  93670. });
  93671. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  93672. get: function () {
  93673. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  93674. var h = (4 * meters) / this.hScreenSize;
  93675. return BABYLON.Matrix.Translation(-h, 0, 0);
  93676. },
  93677. enumerable: true,
  93678. configurable: true
  93679. });
  93680. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  93681. get: function () {
  93682. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  93683. },
  93684. enumerable: true,
  93685. configurable: true
  93686. });
  93687. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  93688. get: function () {
  93689. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  93690. },
  93691. enumerable: true,
  93692. configurable: true
  93693. });
  93694. VRCameraMetrics.GetDefault = function () {
  93695. var result = new VRCameraMetrics();
  93696. result.hResolution = 1280;
  93697. result.vResolution = 800;
  93698. result.hScreenSize = 0.149759993;
  93699. result.vScreenSize = 0.0935999975;
  93700. result.vScreenCenter = 0.0467999987;
  93701. result.eyeToScreenDistance = 0.0410000011;
  93702. result.lensSeparationDistance = 0.0635000020;
  93703. result.interpupillaryDistance = 0.0640000030;
  93704. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  93705. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  93706. result.postProcessScaleFactor = 1.714605507808412;
  93707. result.lensCenterOffset = 0.151976421;
  93708. return result;
  93709. };
  93710. return VRCameraMetrics;
  93711. }());
  93712. BABYLON.VRCameraMetrics = VRCameraMetrics;
  93713. })(BABYLON || (BABYLON = {}));
  93714. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  93715. var BABYLON;
  93716. (function (BABYLON) {
  93717. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  93718. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93719. });
  93720. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  93721. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93722. });
  93723. /**
  93724. * This represents a WebVR camera.
  93725. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  93726. * @example http://doc.babylonjs.com/how_to/webvr_camera
  93727. */
  93728. var WebVRFreeCamera = /** @class */ (function (_super) {
  93729. __extends(WebVRFreeCamera, _super);
  93730. /**
  93731. * Instantiates a WebVRFreeCamera.
  93732. * @param name The name of the WebVRFreeCamera
  93733. * @param position The starting anchor position for the camera
  93734. * @param scene The scene the camera belongs to
  93735. * @param webVROptions a set of customizable options for the webVRCamera
  93736. */
  93737. function WebVRFreeCamera(name, position, scene, webVROptions) {
  93738. if (webVROptions === void 0) { webVROptions = {}; }
  93739. var _this = _super.call(this, name, position, scene) || this;
  93740. _this.webVROptions = webVROptions;
  93741. /**
  93742. * @hidden
  93743. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  93744. */
  93745. _this._vrDevice = null;
  93746. /**
  93747. * The rawPose of the vrDevice.
  93748. */
  93749. _this.rawPose = null;
  93750. _this._specsVersion = "1.1";
  93751. _this._attached = false;
  93752. _this._descendants = [];
  93753. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  93754. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  93755. /** @hidden */
  93756. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  93757. _this._standingMatrix = null;
  93758. /**
  93759. * Represents device position in babylon space.
  93760. */
  93761. _this.devicePosition = BABYLON.Vector3.Zero();
  93762. /**
  93763. * Represents device rotation in babylon space.
  93764. */
  93765. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  93766. /**
  93767. * The scale of the device to be used when translating from device space to babylon space.
  93768. */
  93769. _this.deviceScaleFactor = 1;
  93770. _this._deviceToWorld = BABYLON.Matrix.Identity();
  93771. _this._worldToDevice = BABYLON.Matrix.Identity();
  93772. /**
  93773. * References to the webVR controllers for the vrDevice.
  93774. */
  93775. _this.controllers = [];
  93776. /**
  93777. * Emits an event when a controller is attached.
  93778. */
  93779. _this.onControllersAttachedObservable = new BABYLON.Observable();
  93780. /**
  93781. * Emits an event when a controller's mesh has been loaded;
  93782. */
  93783. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  93784. /**
  93785. * Emits an event when the HMD's pose has been updated.
  93786. */
  93787. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  93788. _this._poseSet = false;
  93789. /**
  93790. * If the rig cameras be used as parent instead of this camera.
  93791. */
  93792. _this.rigParenting = true;
  93793. _this._defaultHeight = undefined;
  93794. _this._workingVector = BABYLON.Vector3.Zero();
  93795. _this._oneVector = BABYLON.Vector3.One();
  93796. _this._workingMatrix = BABYLON.Matrix.Identity();
  93797. _this._cache.position = BABYLON.Vector3.Zero();
  93798. if (webVROptions.defaultHeight) {
  93799. _this._defaultHeight = webVROptions.defaultHeight;
  93800. _this.position.y = _this._defaultHeight;
  93801. }
  93802. _this.minZ = 0.1;
  93803. //legacy support - the compensation boolean was removed.
  93804. if (arguments.length === 5) {
  93805. _this.webVROptions = arguments[4];
  93806. }
  93807. // default webVR options
  93808. if (_this.webVROptions.trackPosition == undefined) {
  93809. _this.webVROptions.trackPosition = true;
  93810. }
  93811. if (_this.webVROptions.controllerMeshes == undefined) {
  93812. _this.webVROptions.controllerMeshes = true;
  93813. }
  93814. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  93815. _this.webVROptions.defaultLightingOnControllers = true;
  93816. }
  93817. _this.rotationQuaternion = new BABYLON.Quaternion();
  93818. if (_this.webVROptions && _this.webVROptions.positionScale) {
  93819. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  93820. }
  93821. //enable VR
  93822. var engine = _this.getEngine();
  93823. _this._onVREnabled = function (success) { if (success) {
  93824. _this.initControllers();
  93825. } };
  93826. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  93827. engine.initWebVR().add(function (event) {
  93828. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  93829. return;
  93830. }
  93831. _this._vrDevice = event.vrDisplay;
  93832. //reset the rig parameters.
  93833. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  93834. if (_this._attached) {
  93835. _this.getEngine().enableVR();
  93836. }
  93837. });
  93838. if (typeof (VRFrameData) !== "undefined")
  93839. _this._frameData = new VRFrameData();
  93840. /**
  93841. * The idea behind the following lines:
  93842. * objects that have the camera as parent should actually have the rig cameras as a parent.
  93843. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  93844. * the second will not show it correctly.
  93845. *
  93846. * To solve this - each object that has the camera as parent will be added to a protected array.
  93847. * When the rig camera renders, it will take this array and set all of those to be its children.
  93848. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  93849. * Amazing!
  93850. */
  93851. scene.onBeforeCameraRenderObservable.add(function (camera) {
  93852. if (camera.parent === _this && _this.rigParenting) {
  93853. _this._descendants = _this.getDescendants(true, function (n) {
  93854. // don't take the cameras or the controllers!
  93855. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  93856. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  93857. return !isController && !isRigCamera;
  93858. });
  93859. _this._descendants.forEach(function (node) {
  93860. node.parent = camera;
  93861. });
  93862. }
  93863. });
  93864. scene.onAfterCameraRenderObservable.add(function (camera) {
  93865. if (camera.parent === _this && _this.rigParenting) {
  93866. _this._descendants.forEach(function (node) {
  93867. node.parent = _this;
  93868. });
  93869. }
  93870. });
  93871. return _this;
  93872. }
  93873. /**
  93874. * Gets the device distance from the ground in meters.
  93875. * @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.
  93876. */
  93877. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  93878. if (this._standingMatrix) {
  93879. // Add standing matrix offset to get real offset from ground in room
  93880. this._standingMatrix.getTranslationToRef(this._workingVector);
  93881. return this._deviceRoomPosition.y + this._workingVector.y;
  93882. }
  93883. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  93884. return this._defaultHeight || 0;
  93885. };
  93886. /**
  93887. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  93888. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  93889. */
  93890. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  93891. var _this = this;
  93892. if (callback === void 0) { callback = function (bool) { }; }
  93893. // Use standing matrix if available
  93894. this.getEngine().initWebVRAsync().then(function (result) {
  93895. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  93896. callback(false);
  93897. }
  93898. else {
  93899. _this._standingMatrix = new BABYLON.Matrix();
  93900. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  93901. if (!_this.getScene().useRightHandedSystem) {
  93902. [2, 6, 8, 9, 14].forEach(function (num) {
  93903. if (_this._standingMatrix) {
  93904. _this._standingMatrix.m[num] *= -1;
  93905. }
  93906. });
  93907. }
  93908. callback(true);
  93909. }
  93910. });
  93911. };
  93912. /**
  93913. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  93914. * @returns A promise with a boolean set to if the standing matrix is supported.
  93915. */
  93916. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  93917. var _this = this;
  93918. return new Promise(function (res, rej) {
  93919. _this.useStandingMatrix(function (supported) {
  93920. res(supported);
  93921. });
  93922. });
  93923. };
  93924. /**
  93925. * Disposes the camera
  93926. */
  93927. WebVRFreeCamera.prototype.dispose = function () {
  93928. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  93929. _super.prototype.dispose.call(this);
  93930. };
  93931. /**
  93932. * Gets a vrController by name.
  93933. * @param name The name of the controller to retreive
  93934. * @returns the controller matching the name specified or null if not found
  93935. */
  93936. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  93937. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  93938. var gp = _a[_i];
  93939. if (gp.hand === name) {
  93940. return gp;
  93941. }
  93942. }
  93943. return null;
  93944. };
  93945. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  93946. /**
  93947. * The controller corrisponding to the users left hand.
  93948. */
  93949. get: function () {
  93950. if (!this._leftController) {
  93951. this._leftController = this.getControllerByName("left");
  93952. }
  93953. return this._leftController;
  93954. },
  93955. enumerable: true,
  93956. configurable: true
  93957. });
  93958. ;
  93959. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  93960. /**
  93961. * The controller corrisponding to the users right hand.
  93962. */
  93963. get: function () {
  93964. if (!this._rightController) {
  93965. this._rightController = this.getControllerByName("right");
  93966. }
  93967. return this._rightController;
  93968. },
  93969. enumerable: true,
  93970. configurable: true
  93971. });
  93972. ;
  93973. /**
  93974. * Casts a ray forward from the vrCamera's gaze.
  93975. * @param length Length of the ray (default: 100)
  93976. * @returns the ray corrisponding to the gaze
  93977. */
  93978. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  93979. if (length === void 0) { length = 100; }
  93980. if (this.leftCamera) {
  93981. // Use left eye to avoid computation to compute center on every call
  93982. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  93983. }
  93984. else {
  93985. return _super.prototype.getForwardRay.call(this, length);
  93986. }
  93987. };
  93988. /**
  93989. * @hidden
  93990. * Updates the camera based on device's frame data
  93991. */
  93992. WebVRFreeCamera.prototype._checkInputs = function () {
  93993. if (this._vrDevice && this._vrDevice.isPresenting) {
  93994. this._vrDevice.getFrameData(this._frameData);
  93995. this.updateFromDevice(this._frameData.pose);
  93996. }
  93997. _super.prototype._checkInputs.call(this);
  93998. };
  93999. /**
  94000. * Updates the poseControlled values based on the input device pose.
  94001. * @param poseData Pose coming from the device
  94002. */
  94003. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  94004. if (poseData && poseData.orientation) {
  94005. this.rawPose = poseData;
  94006. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  94007. if (this.getScene().useRightHandedSystem) {
  94008. this._deviceRoomRotationQuaternion.z *= -1;
  94009. this._deviceRoomRotationQuaternion.w *= -1;
  94010. }
  94011. if (this.webVROptions.trackPosition && this.rawPose.position) {
  94012. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  94013. if (this.getScene().useRightHandedSystem) {
  94014. this._deviceRoomPosition.z *= -1;
  94015. }
  94016. }
  94017. this._poseSet = true;
  94018. }
  94019. };
  94020. /**
  94021. * WebVR's attach control will start broadcasting frames to the device.
  94022. * Note that in certain browsers (chrome for example) this function must be called
  94023. * within a user-interaction callback. Example:
  94024. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  94025. *
  94026. * @param element html element to attach the vrDevice to
  94027. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  94028. */
  94029. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  94030. _super.prototype.attachControl.call(this, element, noPreventDefault);
  94031. this._attached = true;
  94032. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  94033. if (this._vrDevice) {
  94034. this.getEngine().enableVR();
  94035. }
  94036. };
  94037. /**
  94038. * Detaches the camera from the html element and disables VR
  94039. *
  94040. * @param element html element to detach from
  94041. */
  94042. WebVRFreeCamera.prototype.detachControl = function (element) {
  94043. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  94044. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  94045. _super.prototype.detachControl.call(this, element);
  94046. this._attached = false;
  94047. this.getEngine().disableVR();
  94048. };
  94049. /**
  94050. * @returns the name of this class
  94051. */
  94052. WebVRFreeCamera.prototype.getClassName = function () {
  94053. return "WebVRFreeCamera";
  94054. };
  94055. /**
  94056. * Calls resetPose on the vrDisplay
  94057. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  94058. */
  94059. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  94060. //uses the vrDisplay's "resetPose()".
  94061. //pitch and roll won't be affected.
  94062. this._vrDevice.resetPose();
  94063. };
  94064. /**
  94065. * @hidden
  94066. * Updates the rig cameras (left and right eye)
  94067. */
  94068. WebVRFreeCamera.prototype._updateRigCameras = function () {
  94069. var camLeft = this._rigCameras[0];
  94070. var camRight = this._rigCameras[1];
  94071. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  94072. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  94073. camLeft.position.copyFrom(this._deviceRoomPosition);
  94074. camRight.position.copyFrom(this._deviceRoomPosition);
  94075. };
  94076. /**
  94077. * @hidden
  94078. * Updates the cached values of the camera
  94079. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  94080. */
  94081. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  94082. var _this = this;
  94083. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  94084. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  94085. if (!this.updateCacheCalled) {
  94086. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  94087. this.updateCacheCalled = true;
  94088. this.update();
  94089. }
  94090. // Set working vector to the device position in room space rotated by the new rotation
  94091. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  94092. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  94093. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  94094. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  94095. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  94096. // Add translation from anchor position
  94097. this._deviceToWorld.getTranslationToRef(this._workingVector);
  94098. this._workingVector.addInPlace(this.position);
  94099. this._workingVector.subtractInPlace(this._cache.position);
  94100. this._deviceToWorld.setTranslation(this._workingVector);
  94101. // Set an inverted matrix to be used when updating the camera
  94102. this._deviceToWorld.invertToRef(this._worldToDevice);
  94103. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  94104. this.controllers.forEach(function (controller) {
  94105. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  94106. controller.update();
  94107. });
  94108. }
  94109. if (!ignoreParentClass) {
  94110. _super.prototype._updateCache.call(this);
  94111. }
  94112. this.updateCacheCalled = false;
  94113. };
  94114. /**
  94115. * Updates the current device position and rotation in the babylon world
  94116. */
  94117. WebVRFreeCamera.prototype.update = function () {
  94118. // Get current device position in babylon world
  94119. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  94120. // Get current device rotation in babylon world
  94121. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  94122. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  94123. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  94124. if (this._poseSet) {
  94125. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  94126. }
  94127. _super.prototype.update.call(this);
  94128. };
  94129. /**
  94130. * @hidden
  94131. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  94132. * @returns an identity matrix
  94133. */
  94134. WebVRFreeCamera.prototype._getViewMatrix = function () {
  94135. return BABYLON.Matrix.Identity();
  94136. };
  94137. /**
  94138. * This function is called by the two RIG cameras.
  94139. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  94140. */
  94141. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  94142. var _this = this;
  94143. // Update the parent camera prior to using a child camera to avoid desynchronization
  94144. var parentCamera = this._cameraRigParams["parentCamera"];
  94145. parentCamera._updateCache();
  94146. //WebVR 1.1
  94147. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  94148. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  94149. if (!this.getScene().useRightHandedSystem) {
  94150. [2, 6, 8, 9, 14].forEach(function (num) {
  94151. _this._webvrViewMatrix.m[num] *= -1;
  94152. });
  94153. }
  94154. // update the camera rotation matrix
  94155. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  94156. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  94157. // Computing target and final matrix
  94158. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  94159. // should the view matrix be updated with scale and position offset?
  94160. if (parentCamera.deviceScaleFactor !== 1) {
  94161. this._webvrViewMatrix.invert();
  94162. // scale the position, if set
  94163. if (parentCamera.deviceScaleFactor) {
  94164. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  94165. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  94166. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  94167. }
  94168. this._webvrViewMatrix.invert();
  94169. }
  94170. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  94171. // Compute global position
  94172. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  94173. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  94174. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  94175. this._workingMatrix.getTranslationToRef(this._globalPosition);
  94176. this._markSyncedWithParent();
  94177. return this._webvrViewMatrix;
  94178. };
  94179. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  94180. var _this = this;
  94181. var parentCamera = this.parent;
  94182. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  94183. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  94184. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  94185. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  94186. //babylon compatible matrix
  94187. if (!this.getScene().useRightHandedSystem) {
  94188. [8, 9, 10, 11].forEach(function (num) {
  94189. _this._projectionMatrix.m[num] *= -1;
  94190. });
  94191. }
  94192. return this._projectionMatrix;
  94193. };
  94194. /**
  94195. * Initializes the controllers and their meshes
  94196. */
  94197. WebVRFreeCamera.prototype.initControllers = function () {
  94198. var _this = this;
  94199. this.controllers = [];
  94200. var manager = this.getScene().gamepadManager;
  94201. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  94202. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  94203. var webVrController = gamepad;
  94204. if (webVrController.defaultModel) {
  94205. webVrController.defaultModel.setEnabled(false);
  94206. }
  94207. if (webVrController.hand === "right") {
  94208. _this._rightController = null;
  94209. }
  94210. if (webVrController.hand === "left") {
  94211. _this._leftController = null;
  94212. }
  94213. var controllerIndex = _this.controllers.indexOf(webVrController);
  94214. if (controllerIndex !== -1) {
  94215. _this.controllers.splice(controllerIndex, 1);
  94216. }
  94217. }
  94218. });
  94219. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  94220. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  94221. var webVrController_1 = gamepad;
  94222. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  94223. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  94224. if (_this.webVROptions.controllerMeshes) {
  94225. if (webVrController_1.defaultModel) {
  94226. webVrController_1.defaultModel.setEnabled(true);
  94227. }
  94228. else {
  94229. // Load the meshes
  94230. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  94231. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  94232. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  94233. if (_this.webVROptions.defaultLightingOnControllers) {
  94234. if (!_this._lightOnControllers) {
  94235. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  94236. }
  94237. var activateLightOnSubMeshes_1 = function (mesh, light) {
  94238. var children = mesh.getChildren();
  94239. if (children.length !== 0) {
  94240. children.forEach(function (mesh) {
  94241. light.includedOnlyMeshes.push(mesh);
  94242. activateLightOnSubMeshes_1(mesh, light);
  94243. });
  94244. }
  94245. };
  94246. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  94247. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  94248. }
  94249. });
  94250. }
  94251. }
  94252. webVrController_1.attachToPoseControlledCamera(_this);
  94253. // since this is async - sanity check. Is the controller already stored?
  94254. if (_this.controllers.indexOf(webVrController_1) === -1) {
  94255. //add to the controllers array
  94256. _this.controllers.push(webVrController_1);
  94257. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  94258. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  94259. // So we're overriding setting left & right manually to be sure
  94260. var firstViveWandDetected = false;
  94261. for (var i = 0; i < _this.controllers.length; i++) {
  94262. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  94263. if (!firstViveWandDetected) {
  94264. firstViveWandDetected = true;
  94265. _this.controllers[i].hand = "left";
  94266. }
  94267. else {
  94268. _this.controllers[i].hand = "right";
  94269. }
  94270. }
  94271. }
  94272. //did we find enough controllers? Great! let the developer know.
  94273. if (_this.controllers.length >= 2) {
  94274. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  94275. }
  94276. }
  94277. }
  94278. });
  94279. };
  94280. return WebVRFreeCamera;
  94281. }(BABYLON.FreeCamera));
  94282. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  94283. })(BABYLON || (BABYLON = {}));
  94284. //# sourceMappingURL=babylon.webVRCamera.js.map
  94285. var BABYLON;
  94286. (function (BABYLON) {
  94287. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  94288. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  94289. });
  94290. // We're mainly based on the logic defined into the FreeCamera code
  94291. /**
  94292. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  94293. * being tilted forward or back and left or right.
  94294. */
  94295. var DeviceOrientationCamera = /** @class */ (function (_super) {
  94296. __extends(DeviceOrientationCamera, _super);
  94297. /**
  94298. * Creates a new device orientation camera
  94299. * @param name The name of the camera
  94300. * @param position The start position camera
  94301. * @param scene The scene the camera belongs to
  94302. */
  94303. function DeviceOrientationCamera(name, position, scene) {
  94304. var _this = _super.call(this, name, position, scene) || this;
  94305. _this._quaternionCache = new BABYLON.Quaternion();
  94306. _this.inputs.addDeviceOrientation();
  94307. return _this;
  94308. }
  94309. /**
  94310. * Gets the current instance class name ("DeviceOrientationCamera").
  94311. * This helps avoiding instanceof at run time.
  94312. * @returns the class name
  94313. */
  94314. DeviceOrientationCamera.prototype.getClassName = function () {
  94315. return "DeviceOrientationCamera";
  94316. };
  94317. /**
  94318. * @hidden
  94319. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  94320. */
  94321. DeviceOrientationCamera.prototype._checkInputs = function () {
  94322. _super.prototype._checkInputs.call(this);
  94323. this._quaternionCache.copyFrom(this.rotationQuaternion);
  94324. if (this._initialQuaternion) {
  94325. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  94326. }
  94327. };
  94328. /**
  94329. * Reset the camera to its default orientation on the specified axis only.
  94330. * @param axis The axis to reset
  94331. */
  94332. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  94333. var _this = this;
  94334. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  94335. //can only work if this camera has a rotation quaternion already.
  94336. if (!this.rotationQuaternion)
  94337. return;
  94338. if (!this._initialQuaternion) {
  94339. this._initialQuaternion = new BABYLON.Quaternion();
  94340. }
  94341. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  94342. ['x', 'y', 'z'].forEach(function (axisName) {
  94343. if (!axis[axisName]) {
  94344. _this._initialQuaternion[axisName] = 0;
  94345. }
  94346. else {
  94347. _this._initialQuaternion[axisName] *= -1;
  94348. }
  94349. });
  94350. this._initialQuaternion.normalize();
  94351. //force rotation update
  94352. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  94353. };
  94354. return DeviceOrientationCamera;
  94355. }(BABYLON.FreeCamera));
  94356. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  94357. })(BABYLON || (BABYLON = {}));
  94358. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  94359. var BABYLON;
  94360. (function (BABYLON) {
  94361. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  94362. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94363. });
  94364. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  94365. __extends(VRDeviceOrientationFreeCamera, _super);
  94366. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  94367. if (compensateDistortion === void 0) { compensateDistortion = true; }
  94368. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  94369. var _this = _super.call(this, name, position, scene) || this;
  94370. vrCameraMetrics.compensateDistortion = compensateDistortion;
  94371. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  94372. return _this;
  94373. }
  94374. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  94375. return "VRDeviceOrientationFreeCamera";
  94376. };
  94377. return VRDeviceOrientationFreeCamera;
  94378. }(BABYLON.DeviceOrientationCamera));
  94379. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  94380. })(BABYLON || (BABYLON = {}));
  94381. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  94382. var BABYLON;
  94383. (function (BABYLON) {
  94384. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  94385. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  94386. });
  94387. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  94388. __extends(VRDeviceOrientationArcRotateCamera, _super);
  94389. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  94390. if (compensateDistortion === void 0) { compensateDistortion = true; }
  94391. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  94392. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94393. vrCameraMetrics.compensateDistortion = compensateDistortion;
  94394. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  94395. _this.inputs.addVRDeviceOrientation();
  94396. return _this;
  94397. }
  94398. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  94399. return "VRDeviceOrientationArcRotateCamera";
  94400. };
  94401. return VRDeviceOrientationArcRotateCamera;
  94402. }(BABYLON.ArcRotateCamera));
  94403. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  94404. })(BABYLON || (BABYLON = {}));
  94405. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  94406. var BABYLON;
  94407. (function (BABYLON) {
  94408. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  94409. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  94410. });
  94411. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  94412. __extends(VRDeviceOrientationGamepadCamera, _super);
  94413. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  94414. if (compensateDistortion === void 0) { compensateDistortion = true; }
  94415. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  94416. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  94417. _this.inputs.addGamepad();
  94418. return _this;
  94419. }
  94420. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  94421. return "VRDeviceOrientationGamepadCamera";
  94422. };
  94423. return VRDeviceOrientationGamepadCamera;
  94424. }(BABYLON.VRDeviceOrientationFreeCamera));
  94425. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  94426. })(BABYLON || (BABYLON = {}));
  94427. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  94428. var BABYLON;
  94429. (function (BABYLON) {
  94430. var VRExperienceHelperGazer = /** @class */ (function () {
  94431. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  94432. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  94433. this.scene = scene;
  94434. /** @hidden */
  94435. this._pointerDownOnMeshAsked = false;
  94436. /** @hidden */
  94437. this._isActionableMesh = false;
  94438. /** @hidden */
  94439. this._teleportationRequestInitiated = false;
  94440. /** @hidden */
  94441. this._teleportationBackRequestInitiated = false;
  94442. /** @hidden */
  94443. this._rotationRightAsked = false;
  94444. /** @hidden */
  94445. this._rotationLeftAsked = false;
  94446. /** @hidden */
  94447. this._dpadPressed = true;
  94448. /** @hidden */
  94449. this._activePointer = false;
  94450. this._id = VRExperienceHelperGazer._idCounter++;
  94451. // Gaze tracker
  94452. if (!gazeTrackerToClone) {
  94453. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  94454. this._gazeTracker.bakeCurrentTransformIntoVertices();
  94455. this._gazeTracker.isPickable = false;
  94456. this._gazeTracker.isVisible = false;
  94457. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  94458. targetMat.specularColor = BABYLON.Color3.Black();
  94459. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  94460. targetMat.backFaceCulling = false;
  94461. this._gazeTracker.material = targetMat;
  94462. }
  94463. else {
  94464. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  94465. }
  94466. }
  94467. /** @hidden */
  94468. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  94469. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  94470. };
  94471. /** @hidden */
  94472. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  94473. this._pointerDownOnMeshAsked = true;
  94474. if (this._currentHit) {
  94475. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  94476. }
  94477. };
  94478. /** @hidden */
  94479. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  94480. if (this._currentHit) {
  94481. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  94482. }
  94483. this._pointerDownOnMeshAsked = false;
  94484. };
  94485. /** @hidden */
  94486. VRExperienceHelperGazer.prototype._activatePointer = function () {
  94487. this._activePointer = true;
  94488. };
  94489. /** @hidden */
  94490. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  94491. this._activePointer = false;
  94492. };
  94493. /** @hidden */
  94494. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  94495. if (distance === void 0) { distance = 100; }
  94496. };
  94497. VRExperienceHelperGazer.prototype.dispose = function () {
  94498. this._interactionsEnabled = false;
  94499. this._teleportationEnabled = false;
  94500. if (this._gazeTracker) {
  94501. this._gazeTracker.dispose();
  94502. }
  94503. };
  94504. VRExperienceHelperGazer._idCounter = 0;
  94505. return VRExperienceHelperGazer;
  94506. }());
  94507. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  94508. __extends(VRExperienceHelperControllerGazer, _super);
  94509. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  94510. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  94511. _this.webVRController = webVRController;
  94512. // Laser pointer
  94513. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  94514. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  94515. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  94516. laserPointerMaterial.alpha = 0.6;
  94517. _this._laserPointer.material = laserPointerMaterial;
  94518. _this._laserPointer.rotation.x = Math.PI / 2;
  94519. _this._laserPointer.position.z = -0.5;
  94520. _this._laserPointer.isVisible = false;
  94521. _this._laserPointer.isPickable = false;
  94522. if (!webVRController.mesh) {
  94523. // Create an empty mesh that is used prior to loading the high quality model
  94524. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  94525. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  94526. preloadPointerPose.rotation.x = -0.7;
  94527. preloadMesh.addChild(preloadPointerPose);
  94528. webVRController.attachToMesh(preloadMesh);
  94529. }
  94530. _this._setLaserPointerParent(webVRController.mesh);
  94531. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  94532. _this._setLaserPointerParent(mesh);
  94533. });
  94534. return _this;
  94535. }
  94536. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  94537. return this.webVRController.getForwardRay(length);
  94538. };
  94539. /** @hidden */
  94540. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  94541. _super.prototype._activatePointer.call(this);
  94542. this._laserPointer.isVisible = true;
  94543. };
  94544. /** @hidden */
  94545. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  94546. _super.prototype._deactivatePointer.call(this);
  94547. this._laserPointer.isVisible = false;
  94548. };
  94549. /** @hidden */
  94550. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  94551. this._laserPointer.material.emissiveColor = color;
  94552. };
  94553. /** @hidden */
  94554. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  94555. var makeNotPick = function (root) {
  94556. root.isPickable = false;
  94557. root.getChildMeshes().forEach(function (c) {
  94558. makeNotPick(c);
  94559. });
  94560. };
  94561. makeNotPick(mesh);
  94562. var childMeshes = mesh.getChildMeshes();
  94563. this.webVRController._pointingPoseNode = null;
  94564. for (var i = 0; i < childMeshes.length; i++) {
  94565. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  94566. mesh = childMeshes[i];
  94567. this.webVRController._pointingPoseNode = mesh;
  94568. break;
  94569. }
  94570. }
  94571. this._laserPointer.parent = mesh;
  94572. };
  94573. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  94574. if (distance === void 0) { distance = 100; }
  94575. this._laserPointer.scaling.y = distance;
  94576. this._laserPointer.position.z = -distance / 2;
  94577. };
  94578. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  94579. _super.prototype.dispose.call(this);
  94580. this._laserPointer.dispose();
  94581. if (this._meshAttachedObserver) {
  94582. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  94583. }
  94584. };
  94585. return VRExperienceHelperControllerGazer;
  94586. }(VRExperienceHelperGazer));
  94587. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  94588. __extends(VRExperienceHelperCameraGazer, _super);
  94589. function VRExperienceHelperCameraGazer(getCamera, scene) {
  94590. var _this = _super.call(this, scene) || this;
  94591. _this.getCamera = getCamera;
  94592. return _this;
  94593. }
  94594. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  94595. var camera = this.getCamera();
  94596. if (camera) {
  94597. return camera.getForwardRay(length);
  94598. }
  94599. else {
  94600. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  94601. }
  94602. };
  94603. return VRExperienceHelperCameraGazer;
  94604. }(VRExperienceHelperGazer));
  94605. /**
  94606. * Helps to quickly add VR support to an existing scene.
  94607. * See http://doc.babylonjs.com/how_to/webvr_helper
  94608. */
  94609. var VRExperienceHelper = /** @class */ (function () {
  94610. /**
  94611. * Instantiates a VRExperienceHelper.
  94612. * Helps to quickly add VR support to an existing scene.
  94613. * @param scene The scene the VRExperienceHelper belongs to.
  94614. * @param webVROptions Options to modify the vr experience helper's behavior.
  94615. */
  94616. function VRExperienceHelper(scene,
  94617. /** Options to modify the vr experience helper's behavior. */
  94618. webVROptions) {
  94619. if (webVROptions === void 0) { webVROptions = {}; }
  94620. var _this = this;
  94621. this.webVROptions = webVROptions;
  94622. // Can the system support WebVR, even if a headset isn't plugged in?
  94623. this._webVRsupported = false;
  94624. // If WebVR is supported, is a headset plugged in and are we ready to present?
  94625. this._webVRready = false;
  94626. // Are we waiting for the requestPresent callback to complete?
  94627. this._webVRrequesting = false;
  94628. // Are we presenting to the headset right now?
  94629. this._webVRpresenting = false;
  94630. // Are we presenting in the fullscreen fallback?
  94631. this._fullscreenVRpresenting = false;
  94632. /**
  94633. * Observable raised when entering VR.
  94634. */
  94635. this.onEnteringVRObservable = new BABYLON.Observable();
  94636. /**
  94637. * Observable raised when exiting VR.
  94638. */
  94639. this.onExitingVRObservable = new BABYLON.Observable();
  94640. /**
  94641. * Observable raised when controller mesh is loaded.
  94642. */
  94643. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  94644. this._useCustomVRButton = false;
  94645. this._teleportationRequested = false;
  94646. this._teleportActive = false;
  94647. this._floorMeshesCollection = [];
  94648. this._rotationAllowed = true;
  94649. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  94650. this._isDefaultTeleportationTarget = true;
  94651. this._teleportationFillColor = "#444444";
  94652. this._teleportationBorderColor = "#FFFFFF";
  94653. this._rotationAngle = 0;
  94654. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  94655. this._padSensibilityUp = 0.65;
  94656. this._padSensibilityDown = 0.35;
  94657. this.leftController = null;
  94658. this.rightController = null;
  94659. /**
  94660. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  94661. */
  94662. this.onNewMeshSelected = new BABYLON.Observable();
  94663. /**
  94664. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  94665. */
  94666. this.onNewMeshPicked = new BABYLON.Observable();
  94667. /**
  94668. * Observable raised before camera teleportation
  94669. */
  94670. this.onBeforeCameraTeleport = new BABYLON.Observable();
  94671. /**
  94672. * Observable raised after camera teleportation
  94673. */
  94674. this.onAfterCameraTeleport = new BABYLON.Observable();
  94675. /**
  94676. * Observable raised when current selected mesh gets unselected
  94677. */
  94678. this.onSelectedMeshUnselected = new BABYLON.Observable();
  94679. /**
  94680. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  94681. */
  94682. this.teleportationEnabled = true;
  94683. this._teleportationInitialized = false;
  94684. this._interactionsEnabled = false;
  94685. this._interactionsRequested = false;
  94686. this._displayGaze = true;
  94687. this._displayLaserPointer = true;
  94688. this._onResize = function () {
  94689. _this.moveButtonToBottomRight();
  94690. if (_this._fullscreenVRpresenting && _this._webVRready) {
  94691. _this.exitVR();
  94692. }
  94693. };
  94694. this._onFullscreenChange = function () {
  94695. if (document.fullscreen !== undefined) {
  94696. _this._fullscreenVRpresenting = document.fullscreen;
  94697. }
  94698. else if (document.mozFullScreen !== undefined) {
  94699. _this._fullscreenVRpresenting = document.mozFullScreen;
  94700. }
  94701. else if (document.webkitIsFullScreen !== undefined) {
  94702. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  94703. }
  94704. else if (document.msIsFullScreen !== undefined) {
  94705. _this._fullscreenVRpresenting = document.msIsFullScreen;
  94706. }
  94707. else if (document.msFullscreenElement !== undefined) {
  94708. _this._fullscreenVRpresenting = document.msFullscreenElement;
  94709. }
  94710. if (!_this._fullscreenVRpresenting && _this._canvas) {
  94711. _this.exitVR();
  94712. if (!_this._useCustomVRButton) {
  94713. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  94714. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  94715. }
  94716. }
  94717. };
  94718. this.beforeRender = function () {
  94719. if (_this.leftController && _this.leftController._activePointer) {
  94720. _this._castRayAndSelectObject(_this.leftController);
  94721. }
  94722. if (_this.rightController && _this.rightController._activePointer) {
  94723. _this._castRayAndSelectObject(_this.rightController);
  94724. }
  94725. if (_this._noControllerIsActive) {
  94726. _this._castRayAndSelectObject(_this._cameraGazer);
  94727. }
  94728. else {
  94729. _this._cameraGazer._gazeTracker.isVisible = false;
  94730. }
  94731. };
  94732. this._onNewGamepadConnected = function (gamepad) {
  94733. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  94734. if (gamepad.leftStick) {
  94735. gamepad.onleftstickchanged(function (stickValues) {
  94736. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  94737. // Listening to classic/xbox gamepad only if no VR controller is active
  94738. if ((!_this.leftController && !_this.rightController) ||
  94739. ((_this.leftController && !_this.leftController._activePointer) &&
  94740. (_this.rightController && !_this.rightController._activePointer))) {
  94741. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  94742. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  94743. }
  94744. }
  94745. });
  94746. }
  94747. if (gamepad.rightStick) {
  94748. gamepad.onrightstickchanged(function (stickValues) {
  94749. if (_this._teleportationInitialized) {
  94750. _this._checkRotate(stickValues, _this._cameraGazer);
  94751. }
  94752. });
  94753. }
  94754. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  94755. gamepad.onbuttondown(function (buttonPressed) {
  94756. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  94757. _this._cameraGazer._selectionPointerDown();
  94758. }
  94759. });
  94760. gamepad.onbuttonup(function (buttonPressed) {
  94761. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  94762. _this._cameraGazer._selectionPointerUp();
  94763. }
  94764. });
  94765. }
  94766. }
  94767. else {
  94768. var webVRController = gamepad;
  94769. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  94770. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  94771. _this.rightController = controller;
  94772. }
  94773. else {
  94774. _this.leftController = controller;
  94775. }
  94776. _this._tryEnableInteractionOnController(controller);
  94777. }
  94778. };
  94779. // 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
  94780. this._tryEnableInteractionOnController = function (controller) {
  94781. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  94782. _this._enableInteractionOnController(controller);
  94783. }
  94784. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  94785. _this._enableTeleportationOnController(controller);
  94786. }
  94787. };
  94788. this._onNewGamepadDisconnected = function (gamepad) {
  94789. if (gamepad instanceof BABYLON.WebVRController) {
  94790. if (gamepad.hand === "left" && _this.leftController != null) {
  94791. _this.leftController.dispose();
  94792. _this.leftController = null;
  94793. }
  94794. if (gamepad.hand === "right" && _this.rightController != null) {
  94795. _this.rightController.dispose();
  94796. _this.rightController = null;
  94797. }
  94798. }
  94799. };
  94800. this._workingVector = BABYLON.Vector3.Zero();
  94801. this._workingQuaternion = BABYLON.Quaternion.Identity();
  94802. this._workingMatrix = BABYLON.Matrix.Identity();
  94803. this._scene = scene;
  94804. this._canvas = scene.getEngine().getRenderingCanvas();
  94805. // Parse options
  94806. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  94807. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  94808. }
  94809. if (webVROptions.createDeviceOrientationCamera === undefined) {
  94810. webVROptions.createDeviceOrientationCamera = true;
  94811. }
  94812. if (webVROptions.laserToggle === undefined) {
  94813. webVROptions.laserToggle = true;
  94814. }
  94815. if (webVROptions.defaultHeight === undefined) {
  94816. webVROptions.defaultHeight = 1.7;
  94817. }
  94818. if (webVROptions.useCustomVRButton) {
  94819. this._useCustomVRButton = true;
  94820. if (webVROptions.customVRButton) {
  94821. this._btnVR = webVROptions.customVRButton;
  94822. }
  94823. }
  94824. if (webVROptions.rayLength) {
  94825. this._rayLength = webVROptions.rayLength;
  94826. }
  94827. this._defaultHeight = webVROptions.defaultHeight;
  94828. if (webVROptions.positionScale) {
  94829. this._rayLength *= webVROptions.positionScale;
  94830. this._defaultHeight *= webVROptions.positionScale;
  94831. }
  94832. // Set position
  94833. if (this._scene.activeCamera) {
  94834. this._position = this._scene.activeCamera.position.clone();
  94835. }
  94836. else {
  94837. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  94838. }
  94839. // Set non-vr camera
  94840. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  94841. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  94842. // Copy data from existing camera
  94843. if (this._scene.activeCamera) {
  94844. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  94845. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  94846. // Set rotation from previous camera
  94847. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  94848. var targetCamera = this._scene.activeCamera;
  94849. if (targetCamera.rotationQuaternion) {
  94850. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  94851. }
  94852. else {
  94853. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  94854. }
  94855. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  94856. }
  94857. }
  94858. this._scene.activeCamera = this._deviceOrientationCamera;
  94859. if (this._canvas) {
  94860. this._scene.activeCamera.attachControl(this._canvas);
  94861. }
  94862. }
  94863. else {
  94864. this._existingCamera = this._scene.activeCamera;
  94865. }
  94866. // Create VR cameras
  94867. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  94868. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  94869. }
  94870. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  94871. this._webVRCamera.useStandingMatrix();
  94872. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  94873. // Create default button
  94874. if (!this._useCustomVRButton) {
  94875. this._btnVR = document.createElement("BUTTON");
  94876. this._btnVR.className = "babylonVRicon";
  94877. this._btnVR.id = "babylonVRiconbtn";
  94878. this._btnVR.title = "Click to switch to VR";
  94879. 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) }";
  94880. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  94881. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  94882. // css += ".babylonVRicon.vrdisplaysupported { }";
  94883. // css += ".babylonVRicon.vrdisplayready { }";
  94884. // css += ".babylonVRicon.vrdisplayrequesting { }";
  94885. var style = document.createElement('style');
  94886. style.appendChild(document.createTextNode(css));
  94887. document.getElementsByTagName('head')[0].appendChild(style);
  94888. this.moveButtonToBottomRight();
  94889. }
  94890. // VR button click event
  94891. if (this._btnVR) {
  94892. this._btnVR.addEventListener("click", function () {
  94893. if (!_this.isInVRMode) {
  94894. _this.enterVR();
  94895. }
  94896. else {
  94897. _this.exitVR();
  94898. }
  94899. });
  94900. }
  94901. // Window events
  94902. window.addEventListener("resize", this._onResize);
  94903. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  94904. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  94905. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  94906. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  94907. document.onmsfullscreenchange = this._onFullscreenChange;
  94908. // Display vr button when headset is connected
  94909. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  94910. this.displayVRButton();
  94911. }
  94912. else {
  94913. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  94914. if (e.vrDisplay) {
  94915. _this.displayVRButton();
  94916. }
  94917. });
  94918. }
  94919. // Exiting VR mode using 'ESC' key on desktop
  94920. this._onKeyDown = function (event) {
  94921. if (event.keyCode === 27 && _this.isInVRMode) {
  94922. _this.exitVR();
  94923. }
  94924. };
  94925. document.addEventListener("keydown", this._onKeyDown);
  94926. // Exiting VR mode double tapping the touch screen
  94927. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  94928. if (_this.isInVRMode) {
  94929. _this.exitVR();
  94930. if (_this._fullscreenVRpresenting) {
  94931. _this._scene.getEngine().switchFullscreen(true);
  94932. }
  94933. }
  94934. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  94935. // Listen for WebVR display changes
  94936. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  94937. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  94938. this._onVRRequestPresentStart = function () {
  94939. _this._webVRrequesting = true;
  94940. _this.updateButtonVisibility();
  94941. };
  94942. this._onVRRequestPresentComplete = function (success) {
  94943. _this._webVRrequesting = false;
  94944. _this.updateButtonVisibility();
  94945. };
  94946. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  94947. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  94948. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  94949. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94950. scene.onDisposeObservable.add(function () {
  94951. _this.dispose();
  94952. });
  94953. // Gamepad connection events
  94954. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  94955. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  94956. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  94957. this.updateButtonVisibility();
  94958. //create easing functions
  94959. this._circleEase = new BABYLON.CircleEase();
  94960. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  94961. if (this.webVROptions.floorMeshes) {
  94962. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  94963. }
  94964. }
  94965. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  94966. /** Return this.onEnteringVRObservable
  94967. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  94968. */
  94969. get: function () {
  94970. return this.onEnteringVRObservable;
  94971. },
  94972. enumerable: true,
  94973. configurable: true
  94974. });
  94975. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  94976. /** Return this.onExitingVRObservable
  94977. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  94978. */
  94979. get: function () {
  94980. return this.onExitingVRObservable;
  94981. },
  94982. enumerable: true,
  94983. configurable: true
  94984. });
  94985. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  94986. /** Return this.onControllerMeshLoadedObservable
  94987. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  94988. */
  94989. get: function () {
  94990. return this.onControllerMeshLoadedObservable;
  94991. },
  94992. enumerable: true,
  94993. configurable: true
  94994. });
  94995. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  94996. /**
  94997. * The mesh used to display where the user is going to teleport.
  94998. */
  94999. get: function () {
  95000. return this._teleportationTarget;
  95001. },
  95002. /**
  95003. * Sets the mesh to be used to display where the user is going to teleport.
  95004. */
  95005. set: function (value) {
  95006. if (value) {
  95007. value.name = "teleportationTarget";
  95008. this._isDefaultTeleportationTarget = false;
  95009. this._teleportationTarget = value;
  95010. }
  95011. },
  95012. enumerable: true,
  95013. configurable: true
  95014. });
  95015. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  95016. /**
  95017. * The mesh used to display where the user is selecting,
  95018. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  95019. * See http://doc.babylonjs.com/resources/baking_transformations
  95020. */
  95021. get: function () {
  95022. return this._cameraGazer._gazeTracker;
  95023. },
  95024. set: function (value) {
  95025. if (value) {
  95026. this._cameraGazer._gazeTracker = value;
  95027. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  95028. this._cameraGazer._gazeTracker.isPickable = false;
  95029. this._cameraGazer._gazeTracker.isVisible = false;
  95030. this._cameraGazer._gazeTracker.name = "gazeTracker";
  95031. if (this.leftController) {
  95032. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  95033. }
  95034. if (this.rightController) {
  95035. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  95036. }
  95037. }
  95038. },
  95039. enumerable: true,
  95040. configurable: true
  95041. });
  95042. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  95043. /**
  95044. * If the ray of the gaze should be displayed.
  95045. */
  95046. get: function () {
  95047. return this._displayGaze;
  95048. },
  95049. /**
  95050. * Sets if the ray of the gaze should be displayed.
  95051. */
  95052. set: function (value) {
  95053. this._displayGaze = value;
  95054. if (!value) {
  95055. this._cameraGazer._gazeTracker.isVisible = false;
  95056. if (this.leftController) {
  95057. this.leftController._gazeTracker.isVisible = false;
  95058. }
  95059. if (this.rightController) {
  95060. this.rightController._gazeTracker.isVisible = false;
  95061. }
  95062. }
  95063. },
  95064. enumerable: true,
  95065. configurable: true
  95066. });
  95067. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  95068. /**
  95069. * If the ray of the LaserPointer should be displayed.
  95070. */
  95071. get: function () {
  95072. return this._displayLaserPointer;
  95073. },
  95074. /**
  95075. * Sets if the ray of the LaserPointer should be displayed.
  95076. */
  95077. set: function (value) {
  95078. this._displayLaserPointer = value;
  95079. if (!value) {
  95080. if (this.rightController) {
  95081. this.rightController._deactivatePointer();
  95082. this.rightController._gazeTracker.isVisible = false;
  95083. }
  95084. if (this.leftController) {
  95085. this.leftController._deactivatePointer();
  95086. this.leftController._gazeTracker.isVisible = false;
  95087. }
  95088. }
  95089. else {
  95090. if (this.rightController) {
  95091. this.rightController._activatePointer();
  95092. }
  95093. if (this.leftController) {
  95094. this.leftController._activatePointer();
  95095. }
  95096. }
  95097. },
  95098. enumerable: true,
  95099. configurable: true
  95100. });
  95101. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  95102. /**
  95103. * The deviceOrientationCamera used as the camera when not in VR.
  95104. */
  95105. get: function () {
  95106. return this._deviceOrientationCamera;
  95107. },
  95108. enumerable: true,
  95109. configurable: true
  95110. });
  95111. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  95112. /**
  95113. * Based on the current WebVR support, returns the current VR camera used.
  95114. */
  95115. get: function () {
  95116. if (this._webVRready) {
  95117. return this._webVRCamera;
  95118. }
  95119. else {
  95120. return this._scene.activeCamera;
  95121. }
  95122. },
  95123. enumerable: true,
  95124. configurable: true
  95125. });
  95126. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  95127. /**
  95128. * The webVRCamera which is used when in VR.
  95129. */
  95130. get: function () {
  95131. return this._webVRCamera;
  95132. },
  95133. enumerable: true,
  95134. configurable: true
  95135. });
  95136. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  95137. /**
  95138. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  95139. */
  95140. get: function () {
  95141. return this._vrDeviceOrientationCamera;
  95142. },
  95143. enumerable: true,
  95144. configurable: true
  95145. });
  95146. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  95147. get: function () {
  95148. var result = this._cameraGazer._teleportationRequestInitiated
  95149. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  95150. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  95151. return result;
  95152. },
  95153. enumerable: true,
  95154. configurable: true
  95155. });
  95156. // Raised when one of the controller has loaded successfully its associated default mesh
  95157. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  95158. if (this.leftController && this.leftController.webVRController == webVRController) {
  95159. if (webVRController.mesh) {
  95160. this.leftController._setLaserPointerParent(webVRController.mesh);
  95161. }
  95162. }
  95163. if (this.rightController && this.rightController.webVRController == webVRController) {
  95164. if (webVRController.mesh) {
  95165. this.rightController._setLaserPointerParent(webVRController.mesh);
  95166. }
  95167. }
  95168. try {
  95169. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  95170. }
  95171. catch (err) {
  95172. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  95173. }
  95174. };
  95175. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  95176. /**
  95177. * Gets a value indicating if we are currently in VR mode.
  95178. */
  95179. get: function () {
  95180. return this._webVRpresenting || this._fullscreenVRpresenting;
  95181. },
  95182. enumerable: true,
  95183. configurable: true
  95184. });
  95185. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  95186. var vrDisplay = this._scene.getEngine().getVRDevice();
  95187. if (vrDisplay) {
  95188. var wasPresenting = this._webVRpresenting;
  95189. // A VR display is connected
  95190. this._webVRpresenting = vrDisplay.isPresenting;
  95191. if (wasPresenting && !this._webVRpresenting && this.isInVRMode)
  95192. this.exitVR();
  95193. }
  95194. else {
  95195. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  95196. }
  95197. this.updateButtonVisibility();
  95198. };
  95199. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  95200. this._webVRsupported = eventArgs.vrSupported;
  95201. this._webVRready = !!eventArgs.vrDisplay;
  95202. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  95203. this.updateButtonVisibility();
  95204. };
  95205. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  95206. if (this._canvas && !this._useCustomVRButton) {
  95207. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  95208. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  95209. }
  95210. };
  95211. VRExperienceHelper.prototype.displayVRButton = function () {
  95212. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  95213. document.body.appendChild(this._btnVR);
  95214. this._btnVRDisplayed = true;
  95215. }
  95216. };
  95217. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  95218. if (!this._btnVR || this._useCustomVRButton) {
  95219. return;
  95220. }
  95221. this._btnVR.className = "babylonVRicon";
  95222. if (this.isInVRMode) {
  95223. this._btnVR.className += " vrdisplaypresenting";
  95224. }
  95225. else {
  95226. if (this._webVRready)
  95227. this._btnVR.className += " vrdisplayready";
  95228. if (this._webVRsupported)
  95229. this._btnVR.className += " vrdisplaysupported";
  95230. if (this._webVRrequesting)
  95231. this._btnVR.className += " vrdisplayrequesting";
  95232. }
  95233. };
  95234. /**
  95235. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  95236. * Otherwise, will use the fullscreen API.
  95237. */
  95238. VRExperienceHelper.prototype.enterVR = function () {
  95239. if (this.onEnteringVRObservable) {
  95240. try {
  95241. this.onEnteringVRObservable.notifyObservers(this);
  95242. }
  95243. catch (err) {
  95244. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  95245. }
  95246. }
  95247. if (this._scene.activeCamera) {
  95248. this._position = this._scene.activeCamera.position.clone();
  95249. // make sure that we return to the last active camera
  95250. this._existingCamera = this._scene.activeCamera;
  95251. }
  95252. if (this._webVRrequesting)
  95253. return;
  95254. // If WebVR is supported and a headset is connected
  95255. if (this._webVRready) {
  95256. if (!this._webVRpresenting) {
  95257. this._webVRCamera.position = this._position;
  95258. this._scene.activeCamera = this._webVRCamera;
  95259. }
  95260. }
  95261. else if (this._vrDeviceOrientationCamera) {
  95262. this._vrDeviceOrientationCamera.position = this._position;
  95263. if (this._scene.activeCamera) {
  95264. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  95265. }
  95266. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  95267. this._scene.getEngine().switchFullscreen(true);
  95268. this.updateButtonVisibility();
  95269. }
  95270. if (this._scene.activeCamera && this._canvas) {
  95271. this._scene.activeCamera.attachControl(this._canvas);
  95272. }
  95273. if (this._interactionsEnabled) {
  95274. this._scene.registerBeforeRender(this.beforeRender);
  95275. }
  95276. };
  95277. /**
  95278. * Attempt to exit VR, or fullscreen.
  95279. */
  95280. VRExperienceHelper.prototype.exitVR = function () {
  95281. if (this.onExitingVRObservable) {
  95282. try {
  95283. this.onExitingVRObservable.notifyObservers(this);
  95284. }
  95285. catch (err) {
  95286. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  95287. }
  95288. }
  95289. if (this._webVRpresenting) {
  95290. this._scene.getEngine().disableVR();
  95291. }
  95292. if (this._scene.activeCamera) {
  95293. this._position = this._scene.activeCamera.position.clone();
  95294. }
  95295. if (this._deviceOrientationCamera) {
  95296. this._deviceOrientationCamera.position = this._position;
  95297. this._scene.activeCamera = this._deviceOrientationCamera;
  95298. if (this._canvas) {
  95299. this._scene.activeCamera.attachControl(this._canvas);
  95300. }
  95301. }
  95302. else if (this._existingCamera) {
  95303. this._existingCamera.position = this._position;
  95304. this._scene.activeCamera = this._existingCamera;
  95305. }
  95306. this.updateButtonVisibility();
  95307. if (this._interactionsEnabled) {
  95308. this._scene.unregisterBeforeRender(this.beforeRender);
  95309. this._cameraGazer._gazeTracker.isVisible = false;
  95310. if (this.leftController) {
  95311. this.leftController._gazeTracker.isVisible = false;
  95312. }
  95313. if (this.rightController) {
  95314. this.rightController._gazeTracker.isVisible = false;
  95315. }
  95316. }
  95317. // resize to update width and height when exiting vr exits fullscreen
  95318. this._scene.getEngine().resize();
  95319. };
  95320. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  95321. /**
  95322. * The position of the vr experience helper.
  95323. */
  95324. get: function () {
  95325. return this._position;
  95326. },
  95327. /**
  95328. * Sets the position of the vr experience helper.
  95329. */
  95330. set: function (value) {
  95331. this._position = value;
  95332. if (this._scene.activeCamera) {
  95333. this._scene.activeCamera.position = value;
  95334. }
  95335. },
  95336. enumerable: true,
  95337. configurable: true
  95338. });
  95339. /**
  95340. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  95341. */
  95342. VRExperienceHelper.prototype.enableInteractions = function () {
  95343. var _this = this;
  95344. if (!this._interactionsEnabled) {
  95345. this._interactionsRequested = true;
  95346. if (this.leftController) {
  95347. this._enableInteractionOnController(this.leftController);
  95348. }
  95349. if (this.rightController) {
  95350. this._enableInteractionOnController(this.rightController);
  95351. }
  95352. this.raySelectionPredicate = function (mesh) {
  95353. return mesh.isVisible && mesh.isPickable;
  95354. };
  95355. this.meshSelectionPredicate = function (mesh) {
  95356. return true;
  95357. };
  95358. this._raySelectionPredicate = function (mesh) {
  95359. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  95360. && mesh.name.indexOf("teleportationTarget") === -1
  95361. && mesh.name.indexOf("torusTeleportation") === -1)) {
  95362. return _this.raySelectionPredicate(mesh);
  95363. }
  95364. return false;
  95365. };
  95366. this._interactionsEnabled = true;
  95367. }
  95368. };
  95369. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  95370. get: function () {
  95371. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  95372. },
  95373. enumerable: true,
  95374. configurable: true
  95375. });
  95376. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  95377. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  95378. if (this._floorMeshesCollection[i].id === mesh.id) {
  95379. return true;
  95380. }
  95381. }
  95382. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  95383. return true;
  95384. }
  95385. return false;
  95386. };
  95387. /**
  95388. * Adds a floor mesh to be used for teleportation.
  95389. * @param floorMesh the mesh to be used for teleportation.
  95390. */
  95391. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  95392. if (!this._floorMeshesCollection) {
  95393. return;
  95394. }
  95395. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  95396. return;
  95397. }
  95398. this._floorMeshesCollection.push(floorMesh);
  95399. };
  95400. /**
  95401. * Removes a floor mesh from being used for teleportation.
  95402. * @param floorMesh the mesh to be removed.
  95403. */
  95404. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  95405. if (!this._floorMeshesCollection) {
  95406. return;
  95407. }
  95408. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  95409. if (meshIndex !== -1) {
  95410. this._floorMeshesCollection.splice(meshIndex, 1);
  95411. }
  95412. };
  95413. /**
  95414. * Enables interactions and teleportation using the VR controllers and gaze.
  95415. * @param vrTeleportationOptions options to modify teleportation behavior.
  95416. */
  95417. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  95418. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  95419. if (!this._teleportationInitialized) {
  95420. this._teleportationRequested = true;
  95421. this.enableInteractions();
  95422. if (vrTeleportationOptions.floorMeshName) {
  95423. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  95424. }
  95425. if (vrTeleportationOptions.floorMeshes) {
  95426. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  95427. }
  95428. if (this.leftController != null) {
  95429. this._enableTeleportationOnController(this.leftController);
  95430. }
  95431. if (this.rightController != null) {
  95432. this._enableTeleportationOnController(this.rightController);
  95433. }
  95434. // Creates an image processing post process for the vignette not relying
  95435. // on the main scene configuration for image processing to reduce setup and spaces
  95436. // (gamma/linear) conflicts.
  95437. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  95438. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  95439. imageProcessingConfiguration.vignetteEnabled = true;
  95440. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  95441. this._webVRCamera.detachPostProcess(this._postProcessMove);
  95442. this._teleportationInitialized = true;
  95443. if (this._isDefaultTeleportationTarget) {
  95444. this._createTeleportationCircles();
  95445. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  95446. }
  95447. }
  95448. };
  95449. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  95450. var _this = this;
  95451. var controllerMesh = controller.webVRController.mesh;
  95452. if (controllerMesh) {
  95453. controller._interactionsEnabled = true;
  95454. controller._activatePointer();
  95455. if (this.webVROptions.laserToggle) {
  95456. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  95457. // Enabling / disabling laserPointer
  95458. if (_this._displayLaserPointer && stateObject.value === 1) {
  95459. if (controller._activePointer) {
  95460. controller._deactivatePointer();
  95461. }
  95462. else {
  95463. controller._activatePointer();
  95464. }
  95465. if (_this.displayGaze) {
  95466. controller._gazeTracker.isVisible = controller._activePointer;
  95467. }
  95468. }
  95469. });
  95470. }
  95471. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  95472. var gazer = controller;
  95473. if (_this._noControllerIsActive) {
  95474. gazer = _this._cameraGazer;
  95475. }
  95476. if (!gazer._pointerDownOnMeshAsked) {
  95477. if (stateObject.value > _this._padSensibilityUp) {
  95478. gazer._selectionPointerDown();
  95479. }
  95480. }
  95481. else if (stateObject.value < _this._padSensibilityDown) {
  95482. gazer._selectionPointerUp();
  95483. }
  95484. });
  95485. }
  95486. };
  95487. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  95488. // Dont teleport if another gaze already requested teleportation
  95489. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  95490. return;
  95491. }
  95492. if (!gazer._teleportationRequestInitiated) {
  95493. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  95494. gazer._activatePointer();
  95495. gazer._teleportationRequestInitiated = true;
  95496. }
  95497. }
  95498. else {
  95499. // Listening to the proper controller values changes to confirm teleportation
  95500. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  95501. if (this._teleportActive) {
  95502. this._teleportCamera(this._haloCenter);
  95503. }
  95504. gazer._teleportationRequestInitiated = false;
  95505. }
  95506. }
  95507. };
  95508. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  95509. // Only rotate when user is not currently selecting a teleportation location
  95510. if (gazer._teleportationRequestInitiated) {
  95511. return;
  95512. }
  95513. if (!gazer._rotationLeftAsked) {
  95514. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  95515. gazer._rotationLeftAsked = true;
  95516. if (this._rotationAllowed) {
  95517. this._rotateCamera(false);
  95518. }
  95519. }
  95520. }
  95521. else {
  95522. if (stateObject.x > -this._padSensibilityDown) {
  95523. gazer._rotationLeftAsked = false;
  95524. }
  95525. }
  95526. if (!gazer._rotationRightAsked) {
  95527. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  95528. gazer._rotationRightAsked = true;
  95529. if (this._rotationAllowed) {
  95530. this._rotateCamera(true);
  95531. }
  95532. }
  95533. }
  95534. else {
  95535. if (stateObject.x < this._padSensibilityDown) {
  95536. gazer._rotationRightAsked = false;
  95537. }
  95538. }
  95539. };
  95540. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  95541. // Only teleport backwards when user is not currently selecting a teleportation location
  95542. if (gazer._teleportationRequestInitiated) {
  95543. return;
  95544. }
  95545. // Teleport backwards
  95546. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  95547. if (!gazer._teleportationBackRequestInitiated) {
  95548. if (!this.currentVRCamera) {
  95549. return;
  95550. }
  95551. // Get rotation and position of the current camera
  95552. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  95553. var position = this.currentVRCamera.position;
  95554. // If the camera has device position, use that instead
  95555. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  95556. rotation = this.currentVRCamera.deviceRotationQuaternion;
  95557. position = this.currentVRCamera.devicePosition;
  95558. }
  95559. // Get matrix with only the y rotation of the device rotation
  95560. rotation.toEulerAnglesToRef(this._workingVector);
  95561. this._workingVector.z = 0;
  95562. this._workingVector.x = 0;
  95563. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  95564. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  95565. // Rotate backwards ray by device rotation to cast at the ground behind the user
  95566. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  95567. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  95568. var ray = new BABYLON.Ray(position, this._workingVector);
  95569. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  95570. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  95571. this._teleportCamera(hit.pickedPoint);
  95572. }
  95573. gazer._teleportationBackRequestInitiated = true;
  95574. }
  95575. }
  95576. else {
  95577. gazer._teleportationBackRequestInitiated = false;
  95578. }
  95579. };
  95580. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  95581. var _this = this;
  95582. var controllerMesh = controller.webVRController.mesh;
  95583. if (controllerMesh) {
  95584. if (!controller._interactionsEnabled) {
  95585. this._enableInteractionOnController(controller);
  95586. }
  95587. controller._interactionsEnabled = true;
  95588. controller._teleportationEnabled = true;
  95589. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  95590. controller._dpadPressed = false;
  95591. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  95592. controller._dpadPressed = stateObject.pressed;
  95593. if (!controller._dpadPressed) {
  95594. controller._rotationLeftAsked = false;
  95595. controller._rotationRightAsked = false;
  95596. controller._teleportationBackRequestInitiated = false;
  95597. }
  95598. });
  95599. }
  95600. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  95601. if (_this.teleportationEnabled) {
  95602. _this._checkTeleportBackwards(stateObject, controller);
  95603. _this._checkTeleportWithRay(stateObject, controller);
  95604. }
  95605. _this._checkRotate(stateObject, controller);
  95606. });
  95607. }
  95608. };
  95609. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  95610. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  95611. this._teleportationTarget.isPickable = false;
  95612. var length = 512;
  95613. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  95614. dynamicTexture.hasAlpha = true;
  95615. var context = dynamicTexture.getContext();
  95616. var centerX = length / 2;
  95617. var centerY = length / 2;
  95618. var radius = 200;
  95619. context.beginPath();
  95620. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  95621. context.fillStyle = this._teleportationFillColor;
  95622. context.fill();
  95623. context.lineWidth = 10;
  95624. context.strokeStyle = this._teleportationBorderColor;
  95625. context.stroke();
  95626. context.closePath();
  95627. dynamicTexture.update();
  95628. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  95629. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  95630. this._teleportationTarget.material = teleportationCircleMaterial;
  95631. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  95632. torus.isPickable = false;
  95633. torus.parent = this._teleportationTarget;
  95634. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  95635. var keys = [];
  95636. keys.push({
  95637. frame: 0,
  95638. value: 0
  95639. });
  95640. keys.push({
  95641. frame: 30,
  95642. value: 0.4
  95643. });
  95644. keys.push({
  95645. frame: 60,
  95646. value: 0
  95647. });
  95648. animationInnerCircle.setKeys(keys);
  95649. var easingFunction = new BABYLON.SineEase();
  95650. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  95651. animationInnerCircle.setEasingFunction(easingFunction);
  95652. torus.animations = [];
  95653. torus.animations.push(animationInnerCircle);
  95654. this._scene.beginAnimation(torus, 0, 60, true);
  95655. this._hideTeleportationTarget();
  95656. };
  95657. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  95658. this._teleportActive = true;
  95659. if (this._teleportationInitialized) {
  95660. this._teleportationTarget.isVisible = true;
  95661. if (this._isDefaultTeleportationTarget) {
  95662. this._teleportationTarget.getChildren()[0].isVisible = true;
  95663. }
  95664. }
  95665. };
  95666. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  95667. this._teleportActive = false;
  95668. if (this._teleportationInitialized) {
  95669. this._teleportationTarget.isVisible = false;
  95670. if (this._isDefaultTeleportationTarget) {
  95671. this._teleportationTarget.getChildren()[0].isVisible = false;
  95672. }
  95673. }
  95674. };
  95675. VRExperienceHelper.prototype._rotateCamera = function (right) {
  95676. var _this = this;
  95677. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95678. return;
  95679. }
  95680. if (right) {
  95681. this._rotationAngle++;
  95682. }
  95683. else {
  95684. this._rotationAngle--;
  95685. }
  95686. this.currentVRCamera.animations = [];
  95687. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  95688. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95689. var animationRotationKeys = [];
  95690. animationRotationKeys.push({
  95691. frame: 0,
  95692. value: this.currentVRCamera.rotationQuaternion
  95693. });
  95694. animationRotationKeys.push({
  95695. frame: 6,
  95696. value: target
  95697. });
  95698. animationRotation.setKeys(animationRotationKeys);
  95699. animationRotation.setEasingFunction(this._circleEase);
  95700. this.currentVRCamera.animations.push(animationRotation);
  95701. this._postProcessMove.animations = [];
  95702. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95703. var vignetteWeightKeys = [];
  95704. vignetteWeightKeys.push({
  95705. frame: 0,
  95706. value: 0
  95707. });
  95708. vignetteWeightKeys.push({
  95709. frame: 3,
  95710. value: 4
  95711. });
  95712. vignetteWeightKeys.push({
  95713. frame: 6,
  95714. value: 0
  95715. });
  95716. animationPP.setKeys(vignetteWeightKeys);
  95717. animationPP.setEasingFunction(this._circleEase);
  95718. this._postProcessMove.animations.push(animationPP);
  95719. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95720. var vignetteStretchKeys = [];
  95721. vignetteStretchKeys.push({
  95722. frame: 0,
  95723. value: 0
  95724. });
  95725. vignetteStretchKeys.push({
  95726. frame: 3,
  95727. value: 10
  95728. });
  95729. vignetteStretchKeys.push({
  95730. frame: 6,
  95731. value: 0
  95732. });
  95733. animationPP2.setKeys(vignetteStretchKeys);
  95734. animationPP2.setEasingFunction(this._circleEase);
  95735. this._postProcessMove.animations.push(animationPP2);
  95736. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  95737. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  95738. this._postProcessMove.samples = 4;
  95739. this._webVRCamera.attachPostProcess(this._postProcessMove);
  95740. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  95741. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  95742. });
  95743. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  95744. };
  95745. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  95746. if (hit.pickedPoint) {
  95747. if (gazer._teleportationRequestInitiated) {
  95748. this._displayTeleportationTarget();
  95749. this._haloCenter.copyFrom(hit.pickedPoint);
  95750. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  95751. }
  95752. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  95753. if (pickNormal) {
  95754. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  95755. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  95756. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  95757. }
  95758. this._teleportationTarget.position.y += 0.1;
  95759. }
  95760. };
  95761. VRExperienceHelper.prototype._teleportCamera = function (location) {
  95762. var _this = this;
  95763. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95764. return;
  95765. }
  95766. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  95767. // offset of the headset from the anchor.
  95768. if (this.webVRCamera.leftCamera) {
  95769. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  95770. this._workingVector.subtractInPlace(this.webVRCamera.position);
  95771. location.subtractToRef(this._workingVector, this._workingVector);
  95772. }
  95773. else {
  95774. this._workingVector.copyFrom(location);
  95775. }
  95776. // Add height to account for user's height offset
  95777. if (this.isInVRMode) {
  95778. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  95779. }
  95780. else {
  95781. this._workingVector.y += this._defaultHeight;
  95782. }
  95783. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  95784. // Create animation from the camera's position to the new location
  95785. this.currentVRCamera.animations = [];
  95786. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95787. var animationCameraTeleportationKeys = [{
  95788. frame: 0,
  95789. value: this.currentVRCamera.position
  95790. },
  95791. {
  95792. frame: 11,
  95793. value: this._workingVector
  95794. }
  95795. ];
  95796. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  95797. animationCameraTeleportation.setEasingFunction(this._circleEase);
  95798. this.currentVRCamera.animations.push(animationCameraTeleportation);
  95799. this._postProcessMove.animations = [];
  95800. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95801. var vignetteWeightKeys = [];
  95802. vignetteWeightKeys.push({
  95803. frame: 0,
  95804. value: 0
  95805. });
  95806. vignetteWeightKeys.push({
  95807. frame: 5,
  95808. value: 8
  95809. });
  95810. vignetteWeightKeys.push({
  95811. frame: 11,
  95812. value: 0
  95813. });
  95814. animationPP.setKeys(vignetteWeightKeys);
  95815. this._postProcessMove.animations.push(animationPP);
  95816. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  95817. var vignetteStretchKeys = [];
  95818. vignetteStretchKeys.push({
  95819. frame: 0,
  95820. value: 0
  95821. });
  95822. vignetteStretchKeys.push({
  95823. frame: 5,
  95824. value: 10
  95825. });
  95826. vignetteStretchKeys.push({
  95827. frame: 11,
  95828. value: 0
  95829. });
  95830. animationPP2.setKeys(vignetteStretchKeys);
  95831. this._postProcessMove.animations.push(animationPP2);
  95832. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  95833. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  95834. this._webVRCamera.attachPostProcess(this._postProcessMove);
  95835. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  95836. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  95837. });
  95838. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  95839. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  95840. });
  95841. this._hideTeleportationTarget();
  95842. };
  95843. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  95844. if (normal) {
  95845. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  95846. if (angle < Math.PI / 2) {
  95847. normal.scaleInPlace(-1);
  95848. }
  95849. }
  95850. return normal;
  95851. };
  95852. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  95853. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  95854. return;
  95855. }
  95856. var ray = gazer._getForwardRay(this._rayLength);
  95857. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  95858. if (hit) {
  95859. // Populate the contrllers mesh that can be used for drag/drop
  95860. if (gazer._laserPointer) {
  95861. hit.originMesh = gazer._laserPointer.parent;
  95862. }
  95863. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  95864. }
  95865. gazer._currentHit = hit;
  95866. // Moving the gazeTracker on the mesh face targetted
  95867. if (hit && hit.pickedPoint) {
  95868. if (this._displayGaze) {
  95869. var multiplier = 1;
  95870. gazer._gazeTracker.isVisible = true;
  95871. if (gazer._isActionableMesh) {
  95872. multiplier = 3;
  95873. }
  95874. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  95875. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  95876. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  95877. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  95878. // To avoid z-fighting
  95879. var deltaFighting = 0.002;
  95880. if (pickNormal) {
  95881. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  95882. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  95883. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  95884. }
  95885. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  95886. if (gazer._gazeTracker.position.x < 0) {
  95887. gazer._gazeTracker.position.x += deltaFighting;
  95888. }
  95889. else {
  95890. gazer._gazeTracker.position.x -= deltaFighting;
  95891. }
  95892. if (gazer._gazeTracker.position.y < 0) {
  95893. gazer._gazeTracker.position.y += deltaFighting;
  95894. }
  95895. else {
  95896. gazer._gazeTracker.position.y -= deltaFighting;
  95897. }
  95898. if (gazer._gazeTracker.position.z < 0) {
  95899. gazer._gazeTracker.position.z += deltaFighting;
  95900. }
  95901. else {
  95902. gazer._gazeTracker.position.z -= deltaFighting;
  95903. }
  95904. }
  95905. // Changing the size of the laser pointer based on the distance from the targetted point
  95906. gazer._updatePointerDistance(hit.distance);
  95907. }
  95908. else {
  95909. gazer._updatePointerDistance();
  95910. gazer._gazeTracker.isVisible = false;
  95911. }
  95912. if (hit && hit.pickedMesh) {
  95913. // The object selected is the floor, we're in a teleportation scenario
  95914. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  95915. // Moving the teleportation area to this targetted point
  95916. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  95917. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  95918. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95919. }
  95920. gazer._currentMeshSelected = null;
  95921. if (gazer._teleportationRequestInitiated) {
  95922. this._moveTeleportationSelectorTo(hit, gazer, ray);
  95923. }
  95924. return;
  95925. }
  95926. // If not, we're in a selection scenario
  95927. //this._teleportationAllowed = false;
  95928. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  95929. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  95930. this.onNewMeshPicked.notifyObservers(hit);
  95931. gazer._currentMeshSelected = hit.pickedMesh;
  95932. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  95933. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  95934. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  95935. gazer._isActionableMesh = true;
  95936. }
  95937. else {
  95938. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95939. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95940. gazer._isActionableMesh = false;
  95941. }
  95942. try {
  95943. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  95944. }
  95945. catch (err) {
  95946. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  95947. }
  95948. }
  95949. else {
  95950. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95951. gazer._currentMeshSelected = null;
  95952. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95953. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95954. }
  95955. }
  95956. }
  95957. else {
  95958. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  95959. gazer._currentMeshSelected = null;
  95960. //this._teleportationAllowed = false;
  95961. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95962. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  95963. }
  95964. };
  95965. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  95966. if (mesh) {
  95967. this.onSelectedMeshUnselected.notifyObservers(mesh);
  95968. }
  95969. };
  95970. /**
  95971. * Sets the color of the laser ray from the vr controllers.
  95972. * @param color new color for the ray.
  95973. */
  95974. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  95975. if (this.leftController) {
  95976. this.leftController._setLaserPointerColor(color);
  95977. }
  95978. if (this.rightController) {
  95979. this.rightController._setLaserPointerColor(color);
  95980. }
  95981. };
  95982. /**
  95983. * Sets the color of the ray from the vr headsets gaze.
  95984. * @param color new color for the ray.
  95985. */
  95986. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  95987. if (!this._cameraGazer._gazeTracker.material) {
  95988. return;
  95989. }
  95990. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  95991. if (this.leftController) {
  95992. this.leftController._gazeTracker.material.emissiveColor = color;
  95993. }
  95994. if (this.rightController) {
  95995. this.rightController._gazeTracker.material.emissiveColor = color;
  95996. }
  95997. };
  95998. /**
  95999. * Exits VR and disposes of the vr experience helper
  96000. */
  96001. VRExperienceHelper.prototype.dispose = function () {
  96002. if (this.isInVRMode) {
  96003. this.exitVR();
  96004. }
  96005. if (this._postProcessMove) {
  96006. this._postProcessMove.dispose();
  96007. }
  96008. if (this._webVRCamera) {
  96009. this._webVRCamera.dispose();
  96010. }
  96011. if (this._vrDeviceOrientationCamera) {
  96012. this._vrDeviceOrientationCamera.dispose();
  96013. }
  96014. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  96015. document.body.removeChild(this._btnVR);
  96016. }
  96017. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  96018. this._deviceOrientationCamera.dispose();
  96019. }
  96020. if (this._cameraGazer) {
  96021. this._cameraGazer.dispose();
  96022. }
  96023. if (this.leftController) {
  96024. this.leftController.dispose();
  96025. }
  96026. if (this.rightController) {
  96027. this.rightController.dispose();
  96028. }
  96029. if (this._teleportationTarget) {
  96030. this._teleportationTarget.dispose();
  96031. }
  96032. this._floorMeshesCollection = [];
  96033. document.removeEventListener("keydown", this._onKeyDown);
  96034. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96035. window.removeEventListener("resize", this._onResize);
  96036. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  96037. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  96038. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  96039. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  96040. document.onmsfullscreenchange = null;
  96041. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  96042. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  96043. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  96044. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96045. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  96046. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  96047. this._scene.unregisterBeforeRender(this.beforeRender);
  96048. };
  96049. /**
  96050. * Gets the name of the VRExperienceHelper class
  96051. * @returns "VRExperienceHelper"
  96052. */
  96053. VRExperienceHelper.prototype.getClassName = function () {
  96054. return "VRExperienceHelper";
  96055. };
  96056. return VRExperienceHelper;
  96057. }());
  96058. BABYLON.VRExperienceHelper = VRExperienceHelper;
  96059. })(BABYLON || (BABYLON = {}));
  96060. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  96061. // Mainly based on these 2 articles :
  96062. // 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
  96063. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  96064. var BABYLON;
  96065. (function (BABYLON) {
  96066. /**
  96067. * Defines the potential axis of a Joystick
  96068. */
  96069. var JoystickAxis;
  96070. (function (JoystickAxis) {
  96071. /** X axis */
  96072. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  96073. /** Y axis */
  96074. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  96075. /** Z axis */
  96076. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  96077. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  96078. /**
  96079. * Class used to define virtual joystick (used in touch mode)
  96080. */
  96081. var VirtualJoystick = /** @class */ (function () {
  96082. /**
  96083. * Creates a new virtual joystick
  96084. * @param leftJoystick defines that the joystick is for left hand (false by default)
  96085. */
  96086. function VirtualJoystick(leftJoystick) {
  96087. var _this = this;
  96088. if (leftJoystick) {
  96089. this._leftJoystick = true;
  96090. }
  96091. else {
  96092. this._leftJoystick = false;
  96093. }
  96094. VirtualJoystick._globalJoystickIndex++;
  96095. // By default left & right arrow keys are moving the X
  96096. // and up & down keys are moving the Y
  96097. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  96098. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  96099. this.reverseLeftRight = false;
  96100. this.reverseUpDown = false;
  96101. // collections of pointers
  96102. this._touches = new BABYLON.StringDictionary();
  96103. this.deltaPosition = BABYLON.Vector3.Zero();
  96104. this._joystickSensibility = 25;
  96105. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  96106. this._onResize = function (evt) {
  96107. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  96108. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  96109. if (VirtualJoystick.vjCanvas) {
  96110. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  96111. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  96112. }
  96113. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  96114. };
  96115. // injecting a canvas element on top of the canvas 3D game
  96116. if (!VirtualJoystick.vjCanvas) {
  96117. window.addEventListener("resize", this._onResize, false);
  96118. VirtualJoystick.vjCanvas = document.createElement("canvas");
  96119. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  96120. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  96121. VirtualJoystick.vjCanvas.width = window.innerWidth;
  96122. VirtualJoystick.vjCanvas.height = window.innerHeight;
  96123. VirtualJoystick.vjCanvas.style.width = "100%";
  96124. VirtualJoystick.vjCanvas.style.height = "100%";
  96125. VirtualJoystick.vjCanvas.style.position = "absolute";
  96126. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  96127. VirtualJoystick.vjCanvas.style.top = "0px";
  96128. VirtualJoystick.vjCanvas.style.left = "0px";
  96129. VirtualJoystick.vjCanvas.style.zIndex = "5";
  96130. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  96131. // Support for jQuery PEP polyfill
  96132. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  96133. var context = VirtualJoystick.vjCanvas.getContext('2d');
  96134. if (!context) {
  96135. throw new Error("Unable to create canvas for virtual joystick");
  96136. }
  96137. VirtualJoystick.vjCanvasContext = context;
  96138. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  96139. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  96140. document.body.appendChild(VirtualJoystick.vjCanvas);
  96141. }
  96142. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  96143. this.pressed = false;
  96144. // default joystick color
  96145. this._joystickColor = "cyan";
  96146. this._joystickPointerID = -1;
  96147. // current joystick position
  96148. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  96149. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  96150. // origin joystick position
  96151. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  96152. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  96153. this._onPointerDownHandlerRef = function (evt) {
  96154. _this._onPointerDown(evt);
  96155. };
  96156. this._onPointerMoveHandlerRef = function (evt) {
  96157. _this._onPointerMove(evt);
  96158. };
  96159. this._onPointerUpHandlerRef = function (evt) {
  96160. _this._onPointerUp(evt);
  96161. };
  96162. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  96163. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  96164. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  96165. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  96166. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  96167. evt.preventDefault(); // Disables system menu
  96168. }, false);
  96169. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  96170. }
  96171. /**
  96172. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  96173. * @param newJoystickSensibility defines the new sensibility
  96174. */
  96175. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  96176. this._joystickSensibility = newJoystickSensibility;
  96177. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  96178. };
  96179. VirtualJoystick.prototype._onPointerDown = function (e) {
  96180. var positionOnScreenCondition;
  96181. e.preventDefault();
  96182. if (this._leftJoystick === true) {
  96183. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  96184. }
  96185. else {
  96186. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  96187. }
  96188. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  96189. // First contact will be dedicated to the virtual joystick
  96190. this._joystickPointerID = e.pointerId;
  96191. this._joystickPointerStartPos.x = e.clientX;
  96192. this._joystickPointerStartPos.y = e.clientY;
  96193. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  96194. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  96195. this._deltaJoystickVector.x = 0;
  96196. this._deltaJoystickVector.y = 0;
  96197. this.pressed = true;
  96198. this._touches.add(e.pointerId.toString(), e);
  96199. }
  96200. else {
  96201. // You can only trigger the action buttons with a joystick declared
  96202. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  96203. this._action();
  96204. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  96205. }
  96206. }
  96207. };
  96208. VirtualJoystick.prototype._onPointerMove = function (e) {
  96209. // If the current pointer is the one associated to the joystick (first touch contact)
  96210. if (this._joystickPointerID == e.pointerId) {
  96211. this._joystickPointerPos.x = e.clientX;
  96212. this._joystickPointerPos.y = e.clientY;
  96213. this._deltaJoystickVector = this._joystickPointerPos.clone();
  96214. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  96215. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  96216. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  96217. switch (this._axisTargetedByLeftAndRight) {
  96218. case JoystickAxis.X:
  96219. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  96220. break;
  96221. case JoystickAxis.Y:
  96222. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  96223. break;
  96224. case JoystickAxis.Z:
  96225. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  96226. break;
  96227. }
  96228. var directionUpDown = this.reverseUpDown ? 1 : -1;
  96229. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  96230. switch (this._axisTargetedByUpAndDown) {
  96231. case JoystickAxis.X:
  96232. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  96233. break;
  96234. case JoystickAxis.Y:
  96235. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  96236. break;
  96237. case JoystickAxis.Z:
  96238. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  96239. break;
  96240. }
  96241. }
  96242. else {
  96243. var data = this._touches.get(e.pointerId.toString());
  96244. if (data) {
  96245. data.x = e.clientX;
  96246. data.y = e.clientY;
  96247. }
  96248. }
  96249. };
  96250. VirtualJoystick.prototype._onPointerUp = function (e) {
  96251. if (this._joystickPointerID == e.pointerId) {
  96252. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  96253. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  96254. this._joystickPointerID = -1;
  96255. this.pressed = false;
  96256. }
  96257. else {
  96258. var touch = this._touches.get(e.pointerId.toString());
  96259. if (touch) {
  96260. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  96261. }
  96262. }
  96263. this._deltaJoystickVector.x = 0;
  96264. this._deltaJoystickVector.y = 0;
  96265. this._touches.remove(e.pointerId.toString());
  96266. };
  96267. /**
  96268. * Change the color of the virtual joystick
  96269. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  96270. */
  96271. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  96272. this._joystickColor = newColor;
  96273. };
  96274. /**
  96275. * Defines a callback to call when the joystick is touched
  96276. * @param action defines the callback
  96277. */
  96278. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  96279. this._action = action;
  96280. };
  96281. /**
  96282. * Defines which axis you'd like to control for left & right
  96283. * @param axis defines the axis to use
  96284. */
  96285. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  96286. switch (axis) {
  96287. case JoystickAxis.X:
  96288. case JoystickAxis.Y:
  96289. case JoystickAxis.Z:
  96290. this._axisTargetedByLeftAndRight = axis;
  96291. break;
  96292. default:
  96293. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  96294. break;
  96295. }
  96296. };
  96297. /**
  96298. * Defines which axis you'd like to control for up & down
  96299. * @param axis defines the axis to use
  96300. */
  96301. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  96302. switch (axis) {
  96303. case JoystickAxis.X:
  96304. case JoystickAxis.Y:
  96305. case JoystickAxis.Z:
  96306. this._axisTargetedByUpAndDown = axis;
  96307. break;
  96308. default:
  96309. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  96310. break;
  96311. }
  96312. };
  96313. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  96314. var _this = this;
  96315. if (this.pressed) {
  96316. this._touches.forEach(function (key, touch) {
  96317. if (touch.pointerId === _this._joystickPointerID) {
  96318. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  96319. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  96320. VirtualJoystick.vjCanvasContext.beginPath();
  96321. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  96322. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  96323. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  96324. VirtualJoystick.vjCanvasContext.stroke();
  96325. VirtualJoystick.vjCanvasContext.closePath();
  96326. VirtualJoystick.vjCanvasContext.beginPath();
  96327. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  96328. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  96329. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  96330. VirtualJoystick.vjCanvasContext.stroke();
  96331. VirtualJoystick.vjCanvasContext.closePath();
  96332. VirtualJoystick.vjCanvasContext.beginPath();
  96333. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  96334. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  96335. VirtualJoystick.vjCanvasContext.stroke();
  96336. VirtualJoystick.vjCanvasContext.closePath();
  96337. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  96338. }
  96339. else {
  96340. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  96341. VirtualJoystick.vjCanvasContext.beginPath();
  96342. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  96343. VirtualJoystick.vjCanvasContext.beginPath();
  96344. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  96345. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  96346. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  96347. VirtualJoystick.vjCanvasContext.stroke();
  96348. VirtualJoystick.vjCanvasContext.closePath();
  96349. touch.prevX = touch.x;
  96350. touch.prevY = touch.y;
  96351. }
  96352. ;
  96353. });
  96354. }
  96355. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  96356. };
  96357. /**
  96358. * Release internal HTML canvas
  96359. */
  96360. VirtualJoystick.prototype.releaseCanvas = function () {
  96361. if (VirtualJoystick.vjCanvas) {
  96362. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  96363. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  96364. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  96365. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  96366. window.removeEventListener("resize", this._onResize);
  96367. document.body.removeChild(VirtualJoystick.vjCanvas);
  96368. VirtualJoystick.vjCanvas = null;
  96369. }
  96370. };
  96371. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  96372. VirtualJoystick._globalJoystickIndex = 0;
  96373. return VirtualJoystick;
  96374. }());
  96375. BABYLON.VirtualJoystick = VirtualJoystick;
  96376. })(BABYLON || (BABYLON = {}));
  96377. //# sourceMappingURL=babylon.virtualJoystick.js.map
  96378. var BABYLON;
  96379. (function (BABYLON) {
  96380. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  96381. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  96382. });
  96383. // We're mainly based on the logic defined into the FreeCamera code
  96384. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  96385. __extends(VirtualJoysticksCamera, _super);
  96386. function VirtualJoysticksCamera(name, position, scene) {
  96387. var _this = _super.call(this, name, position, scene) || this;
  96388. _this.inputs.addVirtualJoystick();
  96389. return _this;
  96390. }
  96391. VirtualJoysticksCamera.prototype.getClassName = function () {
  96392. return "VirtualJoysticksCamera";
  96393. };
  96394. return VirtualJoysticksCamera;
  96395. }(BABYLON.FreeCamera));
  96396. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  96397. })(BABYLON || (BABYLON = {}));
  96398. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  96399. var BABYLON;
  96400. (function (BABYLON) {
  96401. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  96402. function FreeCameraVirtualJoystickInput() {
  96403. }
  96404. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  96405. return this._leftjoystick;
  96406. };
  96407. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  96408. return this._rightjoystick;
  96409. };
  96410. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  96411. if (this._leftjoystick) {
  96412. var camera = this.camera;
  96413. var speed = camera._computeLocalCameraSpeed() * 50;
  96414. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  96415. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  96416. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  96417. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  96418. if (!this._leftjoystick.pressed) {
  96419. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  96420. }
  96421. if (!this._rightjoystick.pressed) {
  96422. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  96423. }
  96424. }
  96425. };
  96426. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  96427. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  96428. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  96429. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  96430. this._leftjoystick.setJoystickSensibility(0.15);
  96431. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  96432. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  96433. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  96434. this._rightjoystick.reverseUpDown = true;
  96435. this._rightjoystick.setJoystickSensibility(0.05);
  96436. this._rightjoystick.setJoystickColor("yellow");
  96437. };
  96438. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  96439. this._leftjoystick.releaseCanvas();
  96440. this._rightjoystick.releaseCanvas();
  96441. };
  96442. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  96443. return "FreeCameraVirtualJoystickInput";
  96444. };
  96445. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  96446. return "virtualJoystick";
  96447. };
  96448. return FreeCameraVirtualJoystickInput;
  96449. }());
  96450. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  96451. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  96452. })(BABYLON || (BABYLON = {}));
  96453. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  96454. var BABYLON;
  96455. (function (BABYLON) {
  96456. var SimplificationSettings = /** @class */ (function () {
  96457. function SimplificationSettings(quality, distance, optimizeMesh) {
  96458. this.quality = quality;
  96459. this.distance = distance;
  96460. this.optimizeMesh = optimizeMesh;
  96461. }
  96462. return SimplificationSettings;
  96463. }());
  96464. BABYLON.SimplificationSettings = SimplificationSettings;
  96465. var SimplificationQueue = /** @class */ (function () {
  96466. function SimplificationQueue() {
  96467. this.running = false;
  96468. this._simplificationArray = [];
  96469. }
  96470. SimplificationQueue.prototype.addTask = function (task) {
  96471. this._simplificationArray.push(task);
  96472. };
  96473. SimplificationQueue.prototype.executeNext = function () {
  96474. var task = this._simplificationArray.pop();
  96475. if (task) {
  96476. this.running = true;
  96477. this.runSimplification(task);
  96478. }
  96479. else {
  96480. this.running = false;
  96481. }
  96482. };
  96483. SimplificationQueue.prototype.runSimplification = function (task) {
  96484. var _this = this;
  96485. if (task.parallelProcessing) {
  96486. //parallel simplifier
  96487. task.settings.forEach(function (setting) {
  96488. var simplifier = _this.getSimplifier(task);
  96489. simplifier.simplify(setting, function (newMesh) {
  96490. task.mesh.addLODLevel(setting.distance, newMesh);
  96491. newMesh.isVisible = true;
  96492. //check if it is the last
  96493. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  96494. //all done, run the success callback.
  96495. task.successCallback();
  96496. }
  96497. _this.executeNext();
  96498. });
  96499. });
  96500. }
  96501. else {
  96502. //single simplifier.
  96503. var simplifier = this.getSimplifier(task);
  96504. var runDecimation = function (setting, callback) {
  96505. simplifier.simplify(setting, function (newMesh) {
  96506. task.mesh.addLODLevel(setting.distance, newMesh);
  96507. newMesh.isVisible = true;
  96508. //run the next quality level
  96509. callback();
  96510. });
  96511. };
  96512. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  96513. runDecimation(task.settings[loop.index], function () {
  96514. loop.executeNext();
  96515. });
  96516. }, function () {
  96517. //execution ended, run the success callback.
  96518. if (task.successCallback) {
  96519. task.successCallback();
  96520. }
  96521. _this.executeNext();
  96522. });
  96523. }
  96524. };
  96525. SimplificationQueue.prototype.getSimplifier = function (task) {
  96526. switch (task.simplificationType) {
  96527. case SimplificationType.QUADRATIC:
  96528. default:
  96529. return new QuadraticErrorSimplification(task.mesh);
  96530. }
  96531. };
  96532. return SimplificationQueue;
  96533. }());
  96534. BABYLON.SimplificationQueue = SimplificationQueue;
  96535. /**
  96536. * The implemented types of simplification
  96537. * At the moment only Quadratic Error Decimation is implemented
  96538. */
  96539. var SimplificationType;
  96540. (function (SimplificationType) {
  96541. /** Quadratic error decimation */
  96542. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  96543. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  96544. var DecimationTriangle = /** @class */ (function () {
  96545. function DecimationTriangle(vertices) {
  96546. this.vertices = vertices;
  96547. this.error = new Array(4);
  96548. this.deleted = false;
  96549. this.isDirty = false;
  96550. this.deletePending = false;
  96551. this.borderFactor = 0;
  96552. }
  96553. return DecimationTriangle;
  96554. }());
  96555. BABYLON.DecimationTriangle = DecimationTriangle;
  96556. var DecimationVertex = /** @class */ (function () {
  96557. function DecimationVertex(position, id) {
  96558. this.position = position;
  96559. this.id = id;
  96560. this.isBorder = true;
  96561. this.q = new QuadraticMatrix();
  96562. this.triangleCount = 0;
  96563. this.triangleStart = 0;
  96564. this.originalOffsets = [];
  96565. }
  96566. DecimationVertex.prototype.updatePosition = function (newPosition) {
  96567. this.position.copyFrom(newPosition);
  96568. };
  96569. return DecimationVertex;
  96570. }());
  96571. BABYLON.DecimationVertex = DecimationVertex;
  96572. var QuadraticMatrix = /** @class */ (function () {
  96573. function QuadraticMatrix(data) {
  96574. this.data = new Array(10);
  96575. for (var i = 0; i < 10; ++i) {
  96576. if (data && data[i]) {
  96577. this.data[i] = data[i];
  96578. }
  96579. else {
  96580. this.data[i] = 0;
  96581. }
  96582. }
  96583. }
  96584. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  96585. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  96586. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  96587. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  96588. return det;
  96589. };
  96590. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  96591. for (var i = 0; i < 10; ++i) {
  96592. this.data[i] += matrix.data[i];
  96593. }
  96594. };
  96595. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  96596. for (var i = 0; i < 10; ++i) {
  96597. this.data[i] += data[i];
  96598. }
  96599. };
  96600. QuadraticMatrix.prototype.add = function (matrix) {
  96601. var m = new QuadraticMatrix();
  96602. for (var i = 0; i < 10; ++i) {
  96603. m.data[i] = this.data[i] + matrix.data[i];
  96604. }
  96605. return m;
  96606. };
  96607. QuadraticMatrix.FromData = function (a, b, c, d) {
  96608. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  96609. };
  96610. //returning an array to avoid garbage collection
  96611. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  96612. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  96613. };
  96614. return QuadraticMatrix;
  96615. }());
  96616. BABYLON.QuadraticMatrix = QuadraticMatrix;
  96617. var Reference = /** @class */ (function () {
  96618. function Reference(vertexId, triangleId) {
  96619. this.vertexId = vertexId;
  96620. this.triangleId = triangleId;
  96621. }
  96622. return Reference;
  96623. }());
  96624. BABYLON.Reference = Reference;
  96625. /**
  96626. * An implementation of the Quadratic Error simplification algorithm.
  96627. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  96628. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  96629. * @author RaananW
  96630. */
  96631. var QuadraticErrorSimplification = /** @class */ (function () {
  96632. function QuadraticErrorSimplification(_mesh) {
  96633. this._mesh = _mesh;
  96634. this.syncIterations = 5000;
  96635. this.aggressiveness = 7;
  96636. this.decimationIterations = 100;
  96637. this.boundingBoxEpsilon = BABYLON.Epsilon;
  96638. }
  96639. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  96640. var _this = this;
  96641. this.initDecimatedMesh();
  96642. //iterating through the submeshes array, one after the other.
  96643. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  96644. _this.initWithMesh(loop.index, function () {
  96645. _this.runDecimation(settings, loop.index, function () {
  96646. loop.executeNext();
  96647. });
  96648. }, settings.optimizeMesh);
  96649. }, function () {
  96650. setTimeout(function () {
  96651. successCallback(_this._reconstructedMesh);
  96652. }, 0);
  96653. });
  96654. };
  96655. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  96656. var _this = this;
  96657. var targetCount = ~~(this.triangles.length * settings.quality);
  96658. var deletedTriangles = 0;
  96659. var triangleCount = this.triangles.length;
  96660. var iterationFunction = function (iteration, callback) {
  96661. setTimeout(function () {
  96662. if (iteration % 5 === 0) {
  96663. _this.updateMesh(iteration === 0);
  96664. }
  96665. for (var i = 0; i < _this.triangles.length; ++i) {
  96666. _this.triangles[i].isDirty = false;
  96667. }
  96668. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  96669. var trianglesIterator = function (i) {
  96670. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  96671. var t = _this.triangles[tIdx];
  96672. if (!t)
  96673. return;
  96674. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  96675. return;
  96676. }
  96677. for (var j = 0; j < 3; ++j) {
  96678. if (t.error[j] < threshold) {
  96679. var deleted0 = [];
  96680. var deleted1 = [];
  96681. var v0 = t.vertices[j];
  96682. var v1 = t.vertices[(j + 1) % 3];
  96683. if (v0.isBorder || v1.isBorder)
  96684. continue;
  96685. var p = BABYLON.Vector3.Zero();
  96686. var n = BABYLON.Vector3.Zero();
  96687. var uv = BABYLON.Vector2.Zero();
  96688. var color = new BABYLON.Color4(0, 0, 0, 1);
  96689. _this.calculateError(v0, v1, p, n, uv, color);
  96690. var delTr = new Array();
  96691. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  96692. continue;
  96693. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  96694. continue;
  96695. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  96696. continue;
  96697. var uniqueArray = new Array();
  96698. delTr.forEach(function (deletedT) {
  96699. if (uniqueArray.indexOf(deletedT) === -1) {
  96700. deletedT.deletePending = true;
  96701. uniqueArray.push(deletedT);
  96702. }
  96703. });
  96704. if (uniqueArray.length % 2 !== 0) {
  96705. continue;
  96706. }
  96707. v0.q = v1.q.add(v0.q);
  96708. v0.updatePosition(p);
  96709. var tStart = _this.references.length;
  96710. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  96711. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  96712. var tCount = _this.references.length - tStart;
  96713. if (tCount <= v0.triangleCount) {
  96714. if (tCount) {
  96715. for (var c = 0; c < tCount; c++) {
  96716. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  96717. }
  96718. }
  96719. }
  96720. else {
  96721. v0.triangleStart = tStart;
  96722. }
  96723. v0.triangleCount = tCount;
  96724. break;
  96725. }
  96726. }
  96727. };
  96728. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  96729. }, 0);
  96730. };
  96731. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  96732. if (triangleCount - deletedTriangles <= targetCount)
  96733. loop.breakLoop();
  96734. else {
  96735. iterationFunction(loop.index, function () {
  96736. loop.executeNext();
  96737. });
  96738. }
  96739. }, function () {
  96740. setTimeout(function () {
  96741. //reconstruct this part of the mesh
  96742. _this.reconstructMesh(submeshIndex);
  96743. successCallback();
  96744. }, 0);
  96745. });
  96746. };
  96747. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  96748. var _this = this;
  96749. this.vertices = [];
  96750. this.triangles = [];
  96751. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96752. var indices = this._mesh.getIndices();
  96753. var submesh = this._mesh.subMeshes[submeshIndex];
  96754. var findInVertices = function (positionToSearch) {
  96755. if (optimizeMesh) {
  96756. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  96757. if (_this.vertices[ii].position.equals(positionToSearch)) {
  96758. return _this.vertices[ii];
  96759. }
  96760. }
  96761. }
  96762. return null;
  96763. };
  96764. var vertexReferences = [];
  96765. var vertexInit = function (i) {
  96766. if (!positionData) {
  96767. return;
  96768. }
  96769. var offset = i + submesh.verticesStart;
  96770. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  96771. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  96772. vertex.originalOffsets.push(offset);
  96773. if (vertex.id === _this.vertices.length) {
  96774. _this.vertices.push(vertex);
  96775. }
  96776. vertexReferences.push(vertex.id);
  96777. };
  96778. //var totalVertices = mesh.getTotalVertices();
  96779. var totalVertices = submesh.verticesCount;
  96780. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  96781. var indicesInit = function (i) {
  96782. if (!indices) {
  96783. return;
  96784. }
  96785. var offset = (submesh.indexStart / 3) + i;
  96786. var pos = (offset * 3);
  96787. var i0 = indices[pos + 0];
  96788. var i1 = indices[pos + 1];
  96789. var i2 = indices[pos + 2];
  96790. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  96791. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  96792. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  96793. var triangle = new DecimationTriangle([v0, v1, v2]);
  96794. triangle.originalOffset = pos;
  96795. _this.triangles.push(triangle);
  96796. };
  96797. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  96798. _this.init(callback);
  96799. });
  96800. });
  96801. };
  96802. QuadraticErrorSimplification.prototype.init = function (callback) {
  96803. var _this = this;
  96804. var triangleInit1 = function (i) {
  96805. var t = _this.triangles[i];
  96806. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  96807. for (var j = 0; j < 3; j++) {
  96808. 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))));
  96809. }
  96810. };
  96811. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  96812. var triangleInit2 = function (i) {
  96813. var t = _this.triangles[i];
  96814. for (var j = 0; j < 3; ++j) {
  96815. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  96816. }
  96817. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  96818. };
  96819. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  96820. callback();
  96821. });
  96822. });
  96823. };
  96824. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  96825. var newTriangles = [];
  96826. var i;
  96827. for (i = 0; i < this.vertices.length; ++i) {
  96828. this.vertices[i].triangleCount = 0;
  96829. }
  96830. var t;
  96831. var j;
  96832. for (i = 0; i < this.triangles.length; ++i) {
  96833. if (!this.triangles[i].deleted) {
  96834. t = this.triangles[i];
  96835. for (j = 0; j < 3; ++j) {
  96836. t.vertices[j].triangleCount = 1;
  96837. }
  96838. newTriangles.push(t);
  96839. }
  96840. }
  96841. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  96842. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  96843. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  96844. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  96845. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  96846. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  96847. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  96848. var vertexCount = 0;
  96849. for (i = 0; i < this.vertices.length; ++i) {
  96850. var vertex = this.vertices[i];
  96851. vertex.id = vertexCount;
  96852. if (vertex.triangleCount) {
  96853. vertex.originalOffsets.forEach(function (originalOffset) {
  96854. if (!normalData) {
  96855. return;
  96856. }
  96857. newPositionData.push(vertex.position.x);
  96858. newPositionData.push(vertex.position.y);
  96859. newPositionData.push(vertex.position.z);
  96860. newNormalData.push(normalData[originalOffset * 3]);
  96861. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  96862. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  96863. if (uvs && uvs.length) {
  96864. newUVsData.push(uvs[(originalOffset * 2)]);
  96865. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  96866. }
  96867. else if (colorsData && colorsData.length) {
  96868. newColorsData.push(colorsData[(originalOffset * 4)]);
  96869. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  96870. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  96871. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  96872. }
  96873. ++vertexCount;
  96874. });
  96875. }
  96876. }
  96877. var startingIndex = this._reconstructedMesh.getTotalIndices();
  96878. var startingVertex = this._reconstructedMesh.getTotalVertices();
  96879. var submeshesArray = this._reconstructedMesh.subMeshes;
  96880. this._reconstructedMesh.subMeshes = [];
  96881. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  96882. var originalIndices = this._mesh.getIndices();
  96883. for (i = 0; i < newTriangles.length; ++i) {
  96884. t = newTriangles[i]; //now get the new referencing point for each vertex
  96885. [0, 1, 2].forEach(function (idx) {
  96886. var id = originalIndices[t.originalOffset + idx];
  96887. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  96888. if (offset < 0)
  96889. offset = 0;
  96890. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  96891. });
  96892. }
  96893. //overwriting the old vertex buffers and indices.
  96894. this._reconstructedMesh.setIndices(newIndicesArray);
  96895. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  96896. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  96897. if (newUVsData.length > 0)
  96898. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  96899. if (newColorsData.length > 0)
  96900. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  96901. //create submesh
  96902. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  96903. if (submeshIndex > 0) {
  96904. this._reconstructedMesh.subMeshes = [];
  96905. submeshesArray.forEach(function (submesh) {
  96906. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  96907. });
  96908. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  96909. }
  96910. };
  96911. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  96912. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  96913. this._reconstructedMesh.material = this._mesh.material;
  96914. this._reconstructedMesh.parent = this._mesh.parent;
  96915. this._reconstructedMesh.isVisible = false;
  96916. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  96917. };
  96918. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  96919. for (var i = 0; i < vertex1.triangleCount; ++i) {
  96920. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  96921. if (t.deleted)
  96922. continue;
  96923. var s = this.references[vertex1.triangleStart + i].vertexId;
  96924. var v1 = t.vertices[(s + 1) % 3];
  96925. var v2 = t.vertices[(s + 2) % 3];
  96926. if ((v1 === vertex2 || v2 === vertex2)) {
  96927. deletedArray[i] = true;
  96928. delTr.push(t);
  96929. continue;
  96930. }
  96931. var d1 = v1.position.subtract(point);
  96932. d1 = d1.normalize();
  96933. var d2 = v2.position.subtract(point);
  96934. d2 = d2.normalize();
  96935. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  96936. return true;
  96937. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  96938. deletedArray[i] = false;
  96939. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  96940. return true;
  96941. }
  96942. return false;
  96943. };
  96944. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  96945. var newDeleted = deletedTriangles;
  96946. for (var i = 0; i < vertex.triangleCount; ++i) {
  96947. var ref = this.references[vertex.triangleStart + i];
  96948. var t = this.triangles[ref.triangleId];
  96949. if (t.deleted)
  96950. continue;
  96951. if (deletedArray[i] && t.deletePending) {
  96952. t.deleted = true;
  96953. newDeleted++;
  96954. continue;
  96955. }
  96956. t.vertices[ref.vertexId] = origVertex;
  96957. t.isDirty = true;
  96958. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  96959. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  96960. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  96961. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  96962. this.references.push(ref);
  96963. }
  96964. return newDeleted;
  96965. };
  96966. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  96967. for (var i = 0; i < this.vertices.length; ++i) {
  96968. var vCount = [];
  96969. var vId = [];
  96970. var v = this.vertices[i];
  96971. var j;
  96972. for (j = 0; j < v.triangleCount; ++j) {
  96973. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  96974. for (var ii = 0; ii < 3; ii++) {
  96975. var ofs = 0;
  96976. var vv = triangle.vertices[ii];
  96977. while (ofs < vCount.length) {
  96978. if (vId[ofs] === vv.id)
  96979. break;
  96980. ++ofs;
  96981. }
  96982. if (ofs === vCount.length) {
  96983. vCount.push(1);
  96984. vId.push(vv.id);
  96985. }
  96986. else {
  96987. vCount[ofs]++;
  96988. }
  96989. }
  96990. }
  96991. for (j = 0; j < vCount.length; ++j) {
  96992. if (vCount[j] === 1) {
  96993. this.vertices[vId[j]].isBorder = true;
  96994. }
  96995. else {
  96996. this.vertices[vId[j]].isBorder = false;
  96997. }
  96998. }
  96999. }
  97000. };
  97001. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  97002. if (identifyBorders === void 0) { identifyBorders = false; }
  97003. var i;
  97004. if (!identifyBorders) {
  97005. var newTrianglesVector = [];
  97006. for (i = 0; i < this.triangles.length; ++i) {
  97007. if (!this.triangles[i].deleted) {
  97008. newTrianglesVector.push(this.triangles[i]);
  97009. }
  97010. }
  97011. this.triangles = newTrianglesVector;
  97012. }
  97013. for (i = 0; i < this.vertices.length; ++i) {
  97014. this.vertices[i].triangleCount = 0;
  97015. this.vertices[i].triangleStart = 0;
  97016. }
  97017. var t;
  97018. var j;
  97019. var v;
  97020. for (i = 0; i < this.triangles.length; ++i) {
  97021. t = this.triangles[i];
  97022. for (j = 0; j < 3; ++j) {
  97023. v = t.vertices[j];
  97024. v.triangleCount++;
  97025. }
  97026. }
  97027. var tStart = 0;
  97028. for (i = 0; i < this.vertices.length; ++i) {
  97029. this.vertices[i].triangleStart = tStart;
  97030. tStart += this.vertices[i].triangleCount;
  97031. this.vertices[i].triangleCount = 0;
  97032. }
  97033. var newReferences = new Array(this.triangles.length * 3);
  97034. for (i = 0; i < this.triangles.length; ++i) {
  97035. t = this.triangles[i];
  97036. for (j = 0; j < 3; ++j) {
  97037. v = t.vertices[j];
  97038. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  97039. v.triangleCount++;
  97040. }
  97041. }
  97042. this.references = newReferences;
  97043. if (identifyBorders) {
  97044. this.identifyBorder();
  97045. }
  97046. };
  97047. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  97048. var x = point.x;
  97049. var y = point.y;
  97050. var z = point.z;
  97051. 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
  97052. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  97053. };
  97054. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  97055. var q = vertex1.q.add(vertex2.q);
  97056. var border = vertex1.isBorder && vertex2.isBorder;
  97057. var error = 0;
  97058. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  97059. if (qDet !== 0 && !border) {
  97060. if (!pointResult) {
  97061. pointResult = BABYLON.Vector3.Zero();
  97062. }
  97063. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  97064. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  97065. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  97066. error = this.vertexError(q, pointResult);
  97067. }
  97068. else {
  97069. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  97070. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  97071. var error1 = this.vertexError(q, vertex1.position);
  97072. var error2 = this.vertexError(q, vertex2.position);
  97073. var error3 = this.vertexError(q, p3);
  97074. error = Math.min(error1, error2, error3);
  97075. if (error === error1) {
  97076. if (pointResult) {
  97077. pointResult.copyFrom(vertex1.position);
  97078. }
  97079. }
  97080. else if (error === error2) {
  97081. if (pointResult) {
  97082. pointResult.copyFrom(vertex2.position);
  97083. }
  97084. }
  97085. else {
  97086. if (pointResult) {
  97087. pointResult.copyFrom(p3);
  97088. }
  97089. }
  97090. }
  97091. return error;
  97092. };
  97093. return QuadraticErrorSimplification;
  97094. }());
  97095. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  97096. })(BABYLON || (BABYLON = {}));
  97097. //# sourceMappingURL=babylon.meshSimplification.js.map
  97098. var BABYLON;
  97099. (function (BABYLON) {
  97100. var MeshLODLevel = /** @class */ (function () {
  97101. function MeshLODLevel(distance, mesh) {
  97102. this.distance = distance;
  97103. this.mesh = mesh;
  97104. }
  97105. return MeshLODLevel;
  97106. }());
  97107. BABYLON.MeshLODLevel = MeshLODLevel;
  97108. })(BABYLON || (BABYLON = {}));
  97109. //# sourceMappingURL=babylon.meshLODLevel.js.map
  97110. var BABYLON;
  97111. (function (BABYLON) {
  97112. /**
  97113. * Defines the root class used to create scene optimization to use with SceneOptimizer
  97114. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97115. */
  97116. var SceneOptimization = /** @class */ (function () {
  97117. /**
  97118. * Creates the SceneOptimization object
  97119. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97120. * @param desc defines the description associated with the optimization
  97121. */
  97122. function SceneOptimization(
  97123. /**
  97124. * Defines the priority of this optimization (0 by default which means first in the list)
  97125. */
  97126. priority) {
  97127. if (priority === void 0) { priority = 0; }
  97128. this.priority = priority;
  97129. }
  97130. /**
  97131. * Gets a string describing the action executed by the current optimization
  97132. * @returns description string
  97133. */
  97134. SceneOptimization.prototype.getDescription = function () {
  97135. return "";
  97136. };
  97137. /**
  97138. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97139. * @param scene defines the current scene where to apply this optimization
  97140. * @param optimizer defines the current optimizer
  97141. * @returns true if everything that can be done was applied
  97142. */
  97143. SceneOptimization.prototype.apply = function (scene, optimizer) {
  97144. return true;
  97145. };
  97146. ;
  97147. return SceneOptimization;
  97148. }());
  97149. BABYLON.SceneOptimization = SceneOptimization;
  97150. /**
  97151. * Defines an optimization used to reduce the size of render target textures
  97152. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97153. */
  97154. var TextureOptimization = /** @class */ (function (_super) {
  97155. __extends(TextureOptimization, _super);
  97156. /**
  97157. * Creates the TextureOptimization object
  97158. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97159. * @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
  97160. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  97161. */
  97162. function TextureOptimization(
  97163. /**
  97164. * Defines the priority of this optimization (0 by default which means first in the list)
  97165. */
  97166. priority,
  97167. /**
  97168. * 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
  97169. */
  97170. maximumSize,
  97171. /**
  97172. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  97173. */
  97174. step) {
  97175. if (priority === void 0) { priority = 0; }
  97176. if (maximumSize === void 0) { maximumSize = 1024; }
  97177. if (step === void 0) { step = 0.5; }
  97178. var _this = _super.call(this, priority) || this;
  97179. _this.priority = priority;
  97180. _this.maximumSize = maximumSize;
  97181. _this.step = step;
  97182. return _this;
  97183. }
  97184. /**
  97185. * Gets a string describing the action executed by the current optimization
  97186. * @returns description string
  97187. */
  97188. TextureOptimization.prototype.getDescription = function () {
  97189. return "Reducing render target texture size to " + this.maximumSize;
  97190. };
  97191. /**
  97192. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97193. * @param scene defines the current scene where to apply this optimization
  97194. * @param optimizer defines the current optimizer
  97195. * @returns true if everything that can be done was applied
  97196. */
  97197. TextureOptimization.prototype.apply = function (scene, optimizer) {
  97198. var allDone = true;
  97199. for (var index = 0; index < scene.textures.length; index++) {
  97200. var texture = scene.textures[index];
  97201. if (!texture.canRescale || texture.getContext) {
  97202. continue;
  97203. }
  97204. var currentSize = texture.getSize();
  97205. var maxDimension = Math.max(currentSize.width, currentSize.height);
  97206. if (maxDimension > this.maximumSize) {
  97207. texture.scale(this.step);
  97208. allDone = false;
  97209. }
  97210. }
  97211. return allDone;
  97212. };
  97213. return TextureOptimization;
  97214. }(SceneOptimization));
  97215. BABYLON.TextureOptimization = TextureOptimization;
  97216. /**
  97217. * Defines an optimization used to increase or decrease the rendering resolution
  97218. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97219. */
  97220. var HardwareScalingOptimization = /** @class */ (function (_super) {
  97221. __extends(HardwareScalingOptimization, _super);
  97222. /**
  97223. * Creates the HardwareScalingOptimization object
  97224. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97225. * @param maximumScale defines the maximum scale to use (2 by default)
  97226. * @param step defines the step to use between two passes (0.5 by default)
  97227. */
  97228. function HardwareScalingOptimization(
  97229. /**
  97230. * Defines the priority of this optimization (0 by default which means first in the list)
  97231. */
  97232. priority,
  97233. /**
  97234. * Defines the maximum scale to use (2 by default)
  97235. */
  97236. maximumScale,
  97237. /**
  97238. * Defines the step to use between two passes (0.5 by default)
  97239. */
  97240. step) {
  97241. if (priority === void 0) { priority = 0; }
  97242. if (maximumScale === void 0) { maximumScale = 2; }
  97243. if (step === void 0) { step = 0.25; }
  97244. var _this = _super.call(this, priority) || this;
  97245. _this.priority = priority;
  97246. _this.maximumScale = maximumScale;
  97247. _this.step = step;
  97248. _this._currentScale = -1;
  97249. _this._directionOffset = 1;
  97250. return _this;
  97251. }
  97252. /**
  97253. * Gets a string describing the action executed by the current optimization
  97254. * @return description string
  97255. */
  97256. HardwareScalingOptimization.prototype.getDescription = function () {
  97257. return "Setting hardware scaling level to " + this._currentScale;
  97258. };
  97259. /**
  97260. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97261. * @param scene defines the current scene where to apply this optimization
  97262. * @param optimizer defines the current optimizer
  97263. * @returns true if everything that can be done was applied
  97264. */
  97265. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  97266. if (this._currentScale === -1) {
  97267. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  97268. if (this._currentScale > this.maximumScale) {
  97269. this._directionOffset = -1;
  97270. }
  97271. }
  97272. this._currentScale += this._directionOffset * this.step;
  97273. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  97274. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  97275. };
  97276. ;
  97277. return HardwareScalingOptimization;
  97278. }(SceneOptimization));
  97279. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  97280. /**
  97281. * Defines an optimization used to remove shadows
  97282. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97283. */
  97284. var ShadowsOptimization = /** @class */ (function (_super) {
  97285. __extends(ShadowsOptimization, _super);
  97286. function ShadowsOptimization() {
  97287. return _super !== null && _super.apply(this, arguments) || this;
  97288. }
  97289. /**
  97290. * Gets a string describing the action executed by the current optimization
  97291. * @return description string
  97292. */
  97293. ShadowsOptimization.prototype.getDescription = function () {
  97294. return "Turning shadows on/off";
  97295. };
  97296. /**
  97297. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97298. * @param scene defines the current scene where to apply this optimization
  97299. * @param optimizer defines the current optimizer
  97300. * @returns true if everything that can be done was applied
  97301. */
  97302. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  97303. scene.shadowsEnabled = optimizer.isInImprovementMode;
  97304. return true;
  97305. };
  97306. ;
  97307. return ShadowsOptimization;
  97308. }(SceneOptimization));
  97309. BABYLON.ShadowsOptimization = ShadowsOptimization;
  97310. /**
  97311. * Defines an optimization used to turn post-processes off
  97312. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97313. */
  97314. var PostProcessesOptimization = /** @class */ (function (_super) {
  97315. __extends(PostProcessesOptimization, _super);
  97316. function PostProcessesOptimization() {
  97317. return _super !== null && _super.apply(this, arguments) || this;
  97318. }
  97319. /**
  97320. * Gets a string describing the action executed by the current optimization
  97321. * @return description string
  97322. */
  97323. PostProcessesOptimization.prototype.getDescription = function () {
  97324. return "Turning post-processes on/off";
  97325. };
  97326. /**
  97327. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97328. * @param scene defines the current scene where to apply this optimization
  97329. * @param optimizer defines the current optimizer
  97330. * @returns true if everything that can be done was applied
  97331. */
  97332. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  97333. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  97334. return true;
  97335. };
  97336. ;
  97337. return PostProcessesOptimization;
  97338. }(SceneOptimization));
  97339. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  97340. /**
  97341. * Defines an optimization used to turn lens flares off
  97342. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97343. */
  97344. var LensFlaresOptimization = /** @class */ (function (_super) {
  97345. __extends(LensFlaresOptimization, _super);
  97346. function LensFlaresOptimization() {
  97347. return _super !== null && _super.apply(this, arguments) || this;
  97348. }
  97349. /**
  97350. * Gets a string describing the action executed by the current optimization
  97351. * @return description string
  97352. */
  97353. LensFlaresOptimization.prototype.getDescription = function () {
  97354. return "Turning lens flares on/off";
  97355. };
  97356. /**
  97357. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97358. * @param scene defines the current scene where to apply this optimization
  97359. * @param optimizer defines the current optimizer
  97360. * @returns true if everything that can be done was applied
  97361. */
  97362. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  97363. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  97364. return true;
  97365. };
  97366. ;
  97367. return LensFlaresOptimization;
  97368. }(SceneOptimization));
  97369. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  97370. /**
  97371. * Defines an optimization based on user defined callback.
  97372. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97373. */
  97374. var CustomOptimization = /** @class */ (function (_super) {
  97375. __extends(CustomOptimization, _super);
  97376. function CustomOptimization() {
  97377. return _super !== null && _super.apply(this, arguments) || this;
  97378. }
  97379. /**
  97380. * Gets a string describing the action executed by the current optimization
  97381. * @returns description string
  97382. */
  97383. CustomOptimization.prototype.getDescription = function () {
  97384. if (this.onGetDescription) {
  97385. return this.onGetDescription();
  97386. }
  97387. return "Running user defined callback";
  97388. };
  97389. /**
  97390. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97391. * @param scene defines the current scene where to apply this optimization
  97392. * @param optimizer defines the current optimizer
  97393. * @returns true if everything that can be done was applied
  97394. */
  97395. CustomOptimization.prototype.apply = function (scene, optimizer) {
  97396. if (this.onApply) {
  97397. return this.onApply(scene, optimizer);
  97398. }
  97399. return true;
  97400. };
  97401. ;
  97402. return CustomOptimization;
  97403. }(SceneOptimization));
  97404. BABYLON.CustomOptimization = CustomOptimization;
  97405. /**
  97406. * Defines an optimization used to turn particles off
  97407. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97408. */
  97409. var ParticlesOptimization = /** @class */ (function (_super) {
  97410. __extends(ParticlesOptimization, _super);
  97411. function ParticlesOptimization() {
  97412. return _super !== null && _super.apply(this, arguments) || this;
  97413. }
  97414. /**
  97415. * Gets a string describing the action executed by the current optimization
  97416. * @return description string
  97417. */
  97418. ParticlesOptimization.prototype.getDescription = function () {
  97419. return "Turning particles on/off";
  97420. };
  97421. /**
  97422. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97423. * @param scene defines the current scene where to apply this optimization
  97424. * @param optimizer defines the current optimizer
  97425. * @returns true if everything that can be done was applied
  97426. */
  97427. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  97428. scene.particlesEnabled = optimizer.isInImprovementMode;
  97429. return true;
  97430. };
  97431. ;
  97432. return ParticlesOptimization;
  97433. }(SceneOptimization));
  97434. BABYLON.ParticlesOptimization = ParticlesOptimization;
  97435. /**
  97436. * Defines an optimization used to turn render targets off
  97437. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97438. */
  97439. var RenderTargetsOptimization = /** @class */ (function (_super) {
  97440. __extends(RenderTargetsOptimization, _super);
  97441. function RenderTargetsOptimization() {
  97442. return _super !== null && _super.apply(this, arguments) || this;
  97443. }
  97444. /**
  97445. * Gets a string describing the action executed by the current optimization
  97446. * @return description string
  97447. */
  97448. RenderTargetsOptimization.prototype.getDescription = function () {
  97449. return "Turning render targets off";
  97450. };
  97451. /**
  97452. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97453. * @param scene defines the current scene where to apply this optimization
  97454. * @param optimizer defines the current optimizer
  97455. * @returns true if everything that can be done was applied
  97456. */
  97457. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  97458. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  97459. return true;
  97460. };
  97461. ;
  97462. return RenderTargetsOptimization;
  97463. }(SceneOptimization));
  97464. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  97465. /**
  97466. * Defines an optimization used to merge meshes with compatible materials
  97467. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97468. */
  97469. var MergeMeshesOptimization = /** @class */ (function (_super) {
  97470. __extends(MergeMeshesOptimization, _super);
  97471. function MergeMeshesOptimization() {
  97472. var _this = _super !== null && _super.apply(this, arguments) || this;
  97473. _this._canBeMerged = function (abstractMesh) {
  97474. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  97475. return false;
  97476. }
  97477. var mesh = abstractMesh;
  97478. if (mesh.isDisposed()) {
  97479. return false;
  97480. }
  97481. if (!mesh.isVisible || !mesh.isEnabled()) {
  97482. return false;
  97483. }
  97484. if (mesh.instances.length > 0) {
  97485. return false;
  97486. }
  97487. if (mesh.skeleton || mesh.hasLODLevels) {
  97488. return false;
  97489. }
  97490. return true;
  97491. };
  97492. return _this;
  97493. }
  97494. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  97495. /**
  97496. * Gets or sets a boolean which defines if optimization octree has to be updated
  97497. */
  97498. get: function () {
  97499. return MergeMeshesOptimization._UpdateSelectionTree;
  97500. },
  97501. /**
  97502. * Gets or sets a boolean which defines if optimization octree has to be updated
  97503. */
  97504. set: function (value) {
  97505. MergeMeshesOptimization._UpdateSelectionTree = value;
  97506. },
  97507. enumerable: true,
  97508. configurable: true
  97509. });
  97510. /**
  97511. * Gets a string describing the action executed by the current optimization
  97512. * @return description string
  97513. */
  97514. MergeMeshesOptimization.prototype.getDescription = function () {
  97515. return "Merging similar meshes together";
  97516. };
  97517. /**
  97518. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97519. * @param scene defines the current scene where to apply this optimization
  97520. * @param optimizer defines the current optimizer
  97521. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  97522. * @returns true if everything that can be done was applied
  97523. */
  97524. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  97525. var globalPool = scene.meshes.slice(0);
  97526. var globalLength = globalPool.length;
  97527. for (var index = 0; index < globalLength; index++) {
  97528. var currentPool = new Array();
  97529. var current = globalPool[index];
  97530. // Checks
  97531. if (!this._canBeMerged(current)) {
  97532. continue;
  97533. }
  97534. currentPool.push(current);
  97535. // Find compatible meshes
  97536. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  97537. var otherMesh = globalPool[subIndex];
  97538. if (!this._canBeMerged(otherMesh)) {
  97539. continue;
  97540. }
  97541. if (otherMesh.material !== current.material) {
  97542. continue;
  97543. }
  97544. if (otherMesh.checkCollisions !== current.checkCollisions) {
  97545. continue;
  97546. }
  97547. currentPool.push(otherMesh);
  97548. globalLength--;
  97549. globalPool.splice(subIndex, 1);
  97550. subIndex--;
  97551. }
  97552. if (currentPool.length < 2) {
  97553. continue;
  97554. }
  97555. // Merge meshes
  97556. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  97557. }
  97558. if (updateSelectionTree != undefined) {
  97559. if (updateSelectionTree) {
  97560. scene.createOrUpdateSelectionOctree();
  97561. }
  97562. }
  97563. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  97564. scene.createOrUpdateSelectionOctree();
  97565. }
  97566. return true;
  97567. };
  97568. ;
  97569. MergeMeshesOptimization._UpdateSelectionTree = false;
  97570. return MergeMeshesOptimization;
  97571. }(SceneOptimization));
  97572. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  97573. /**
  97574. * Defines a list of options used by SceneOptimizer
  97575. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97576. */
  97577. var SceneOptimizerOptions = /** @class */ (function () {
  97578. /**
  97579. * Creates a new list of options used by SceneOptimizer
  97580. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  97581. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  97582. */
  97583. function SceneOptimizerOptions(
  97584. /**
  97585. * Defines the target frame rate to reach (60 by default)
  97586. */
  97587. targetFrameRate,
  97588. /**
  97589. * Defines the interval between two checkes (2000ms by default)
  97590. */
  97591. trackerDuration) {
  97592. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  97593. if (trackerDuration === void 0) { trackerDuration = 2000; }
  97594. this.targetFrameRate = targetFrameRate;
  97595. this.trackerDuration = trackerDuration;
  97596. /**
  97597. * Gets the list of optimizations to apply
  97598. */
  97599. this.optimizations = new Array();
  97600. }
  97601. /**
  97602. * Add a new optimization
  97603. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  97604. * @returns the current SceneOptimizerOptions
  97605. */
  97606. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  97607. this.optimizations.push(optimization);
  97608. return this;
  97609. };
  97610. /**
  97611. * Add a new custom optimization
  97612. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  97613. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  97614. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97615. * @returns the current SceneOptimizerOptions
  97616. */
  97617. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  97618. if (priority === void 0) { priority = 0; }
  97619. var optimization = new CustomOptimization(priority);
  97620. optimization.onApply = onApply;
  97621. optimization.onGetDescription = onGetDescription;
  97622. this.optimizations.push(optimization);
  97623. return this;
  97624. };
  97625. /**
  97626. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  97627. * @param targetFrameRate defines the target frame rate (60 by default)
  97628. * @returns a SceneOptimizerOptions object
  97629. */
  97630. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  97631. var result = new SceneOptimizerOptions(targetFrameRate);
  97632. var priority = 0;
  97633. result.addOptimization(new MergeMeshesOptimization(priority));
  97634. result.addOptimization(new ShadowsOptimization(priority));
  97635. result.addOptimization(new LensFlaresOptimization(priority));
  97636. // Next priority
  97637. priority++;
  97638. result.addOptimization(new PostProcessesOptimization(priority));
  97639. result.addOptimization(new ParticlesOptimization(priority));
  97640. // Next priority
  97641. priority++;
  97642. result.addOptimization(new TextureOptimization(priority, 1024));
  97643. return result;
  97644. };
  97645. /**
  97646. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  97647. * @param targetFrameRate defines the target frame rate (60 by default)
  97648. * @returns a SceneOptimizerOptions object
  97649. */
  97650. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  97651. var result = new SceneOptimizerOptions(targetFrameRate);
  97652. var priority = 0;
  97653. result.addOptimization(new MergeMeshesOptimization(priority));
  97654. result.addOptimization(new ShadowsOptimization(priority));
  97655. result.addOptimization(new LensFlaresOptimization(priority));
  97656. // Next priority
  97657. priority++;
  97658. result.addOptimization(new PostProcessesOptimization(priority));
  97659. result.addOptimization(new ParticlesOptimization(priority));
  97660. // Next priority
  97661. priority++;
  97662. result.addOptimization(new TextureOptimization(priority, 512));
  97663. // Next priority
  97664. priority++;
  97665. result.addOptimization(new RenderTargetsOptimization(priority));
  97666. // Next priority
  97667. priority++;
  97668. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  97669. return result;
  97670. };
  97671. /**
  97672. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  97673. * @param targetFrameRate defines the target frame rate (60 by default)
  97674. * @returns a SceneOptimizerOptions object
  97675. */
  97676. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  97677. var result = new SceneOptimizerOptions(targetFrameRate);
  97678. var priority = 0;
  97679. result.addOptimization(new MergeMeshesOptimization(priority));
  97680. result.addOptimization(new ShadowsOptimization(priority));
  97681. result.addOptimization(new LensFlaresOptimization(priority));
  97682. // Next priority
  97683. priority++;
  97684. result.addOptimization(new PostProcessesOptimization(priority));
  97685. result.addOptimization(new ParticlesOptimization(priority));
  97686. // Next priority
  97687. priority++;
  97688. result.addOptimization(new TextureOptimization(priority, 256));
  97689. // Next priority
  97690. priority++;
  97691. result.addOptimization(new RenderTargetsOptimization(priority));
  97692. // Next priority
  97693. priority++;
  97694. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  97695. return result;
  97696. };
  97697. return SceneOptimizerOptions;
  97698. }());
  97699. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  97700. /**
  97701. * Class used to run optimizations in order to reach a target frame rate
  97702. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97703. */
  97704. var SceneOptimizer = /** @class */ (function () {
  97705. /**
  97706. * Creates a new SceneOptimizer
  97707. * @param scene defines the scene to work on
  97708. * @param options defines the options to use with the SceneOptimizer
  97709. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  97710. * @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)
  97711. */
  97712. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  97713. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  97714. if (improvementMode === void 0) { improvementMode = false; }
  97715. var _this = this;
  97716. this._isRunning = false;
  97717. this._currentPriorityLevel = 0;
  97718. this._targetFrameRate = 60;
  97719. this._trackerDuration = 2000;
  97720. this._currentFrameRate = 0;
  97721. this._improvementMode = false;
  97722. /**
  97723. * Defines an observable called when the optimizer reaches the target frame rate
  97724. */
  97725. this.onSuccessObservable = new BABYLON.Observable();
  97726. /**
  97727. * Defines an observable called when the optimizer enables an optimization
  97728. */
  97729. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  97730. /**
  97731. * Defines an observable called when the optimizer is not able to reach the target frame rate
  97732. */
  97733. this.onFailureObservable = new BABYLON.Observable();
  97734. if (!options) {
  97735. this._options = new SceneOptimizerOptions();
  97736. }
  97737. else {
  97738. this._options = options;
  97739. }
  97740. if (this._options.targetFrameRate) {
  97741. this._targetFrameRate = this._options.targetFrameRate;
  97742. }
  97743. if (this._options.trackerDuration) {
  97744. this._trackerDuration = this._options.trackerDuration;
  97745. }
  97746. if (autoGeneratePriorities) {
  97747. var priority = 0;
  97748. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  97749. var optim = _a[_i];
  97750. optim.priority = priority++;
  97751. }
  97752. }
  97753. this._improvementMode = improvementMode;
  97754. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97755. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  97756. _this._sceneDisposeObserver = null;
  97757. _this.dispose();
  97758. });
  97759. }
  97760. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  97761. /**
  97762. * Gets a boolean indicating if the optimizer is in improvement mode
  97763. */
  97764. get: function () {
  97765. return this._improvementMode;
  97766. },
  97767. enumerable: true,
  97768. configurable: true
  97769. });
  97770. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  97771. /**
  97772. * Gets the current priority level (0 at start)
  97773. */
  97774. get: function () {
  97775. return this._currentPriorityLevel;
  97776. },
  97777. enumerable: true,
  97778. configurable: true
  97779. });
  97780. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  97781. /**
  97782. * Gets the current frame rate checked by the SceneOptimizer
  97783. */
  97784. get: function () {
  97785. return this._currentFrameRate;
  97786. },
  97787. enumerable: true,
  97788. configurable: true
  97789. });
  97790. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  97791. /**
  97792. * Gets or sets the current target frame rate (60 by default)
  97793. */
  97794. get: function () {
  97795. return this._targetFrameRate;
  97796. },
  97797. /**
  97798. * Gets or sets the current target frame rate (60 by default)
  97799. */
  97800. set: function (value) {
  97801. this._targetFrameRate = value;
  97802. },
  97803. enumerable: true,
  97804. configurable: true
  97805. });
  97806. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  97807. /**
  97808. * Gets or sets the current interval between two checks (every 2000ms by default)
  97809. */
  97810. get: function () {
  97811. return this._trackerDuration;
  97812. },
  97813. /**
  97814. * Gets or sets the current interval between two checks (every 2000ms by default)
  97815. */
  97816. set: function (value) {
  97817. this._trackerDuration = value;
  97818. },
  97819. enumerable: true,
  97820. configurable: true
  97821. });
  97822. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  97823. /**
  97824. * Gets the list of active optimizations
  97825. */
  97826. get: function () {
  97827. return this._options.optimizations;
  97828. },
  97829. enumerable: true,
  97830. configurable: true
  97831. });
  97832. /**
  97833. * Stops the current optimizer
  97834. */
  97835. SceneOptimizer.prototype.stop = function () {
  97836. this._isRunning = false;
  97837. };
  97838. /**
  97839. * Reset the optimizer to initial step (current priority level = 0)
  97840. */
  97841. SceneOptimizer.prototype.reset = function () {
  97842. this._currentPriorityLevel = 0;
  97843. };
  97844. /**
  97845. * Start the optimizer. By default it will try to reach a specific framerate
  97846. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  97847. */
  97848. SceneOptimizer.prototype.start = function () {
  97849. var _this = this;
  97850. if (this._isRunning) {
  97851. return;
  97852. }
  97853. this._isRunning = true;
  97854. // Let's wait for the scene to be ready before running our check
  97855. this._scene.executeWhenReady(function () {
  97856. setTimeout(function () {
  97857. _this._checkCurrentState();
  97858. }, _this._trackerDuration);
  97859. });
  97860. };
  97861. SceneOptimizer.prototype._checkCurrentState = function () {
  97862. var _this = this;
  97863. if (!this._isRunning) {
  97864. return;
  97865. }
  97866. var scene = this._scene;
  97867. var options = this._options;
  97868. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  97869. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  97870. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  97871. this._isRunning = false;
  97872. this.onSuccessObservable.notifyObservers(this);
  97873. return;
  97874. }
  97875. // Apply current level of optimizations
  97876. var allDone = true;
  97877. var noOptimizationApplied = true;
  97878. for (var index = 0; index < options.optimizations.length; index++) {
  97879. var optimization = options.optimizations[index];
  97880. if (optimization.priority === this._currentPriorityLevel) {
  97881. noOptimizationApplied = false;
  97882. allDone = allDone && optimization.apply(scene, this);
  97883. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  97884. }
  97885. }
  97886. // If no optimization was applied, this is a failure :(
  97887. if (noOptimizationApplied) {
  97888. this._isRunning = false;
  97889. this.onFailureObservable.notifyObservers(this);
  97890. return;
  97891. }
  97892. // If all optimizations were done, move to next level
  97893. if (allDone) {
  97894. this._currentPriorityLevel++;
  97895. }
  97896. // Let's the system running for a specific amount of time before checking FPS
  97897. scene.executeWhenReady(function () {
  97898. setTimeout(function () {
  97899. _this._checkCurrentState();
  97900. }, _this._trackerDuration);
  97901. });
  97902. };
  97903. /**
  97904. * Release all resources
  97905. */
  97906. SceneOptimizer.prototype.dispose = function () {
  97907. this.stop();
  97908. this.onSuccessObservable.clear();
  97909. this.onFailureObservable.clear();
  97910. this.onNewOptimizationAppliedObservable.clear();
  97911. if (this._sceneDisposeObserver) {
  97912. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  97913. }
  97914. };
  97915. /**
  97916. * Helper function to create a SceneOptimizer with one single line of code
  97917. * @param scene defines the scene to work on
  97918. * @param options defines the options to use with the SceneOptimizer
  97919. * @param onSuccess defines a callback to call on success
  97920. * @param onFailure defines a callback to call on failure
  97921. * @returns the new SceneOptimizer object
  97922. */
  97923. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  97924. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  97925. if (onSuccess) {
  97926. optimizer.onSuccessObservable.add(function () {
  97927. onSuccess();
  97928. });
  97929. }
  97930. if (onFailure) {
  97931. optimizer.onFailureObservable.add(function () {
  97932. onFailure();
  97933. });
  97934. }
  97935. optimizer.start();
  97936. return optimizer;
  97937. };
  97938. return SceneOptimizer;
  97939. }());
  97940. BABYLON.SceneOptimizer = SceneOptimizer;
  97941. })(BABYLON || (BABYLON = {}));
  97942. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  97943. var BABYLON;
  97944. (function (BABYLON) {
  97945. var OutlineRenderer = /** @class */ (function () {
  97946. function OutlineRenderer(scene) {
  97947. this.zOffset = 1;
  97948. this._scene = scene;
  97949. }
  97950. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  97951. var _this = this;
  97952. if (useOverlay === void 0) { useOverlay = false; }
  97953. var scene = this._scene;
  97954. var engine = this._scene.getEngine();
  97955. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97956. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  97957. return;
  97958. }
  97959. var mesh = subMesh.getRenderingMesh();
  97960. var material = subMesh.getMaterial();
  97961. if (!material || !scene.activeCamera) {
  97962. return;
  97963. }
  97964. engine.enableEffect(this._effect);
  97965. // Logarithmic depth
  97966. if (material.useLogarithmicDepth) {
  97967. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  97968. }
  97969. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  97970. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  97971. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  97972. // Bones
  97973. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97974. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97975. }
  97976. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  97977. // Alpha test
  97978. if (material && material.needAlphaTesting()) {
  97979. var alphaTexture = material.getAlphaTestTexture();
  97980. if (alphaTexture) {
  97981. this._effect.setTexture("diffuseSampler", alphaTexture);
  97982. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  97983. }
  97984. }
  97985. engine.setZOffset(-this.zOffset);
  97986. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  97987. engine.setZOffset(0);
  97988. };
  97989. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  97990. var defines = [];
  97991. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  97992. var mesh = subMesh.getMesh();
  97993. var material = subMesh.getMaterial();
  97994. if (material) {
  97995. // Alpha test
  97996. if (material.needAlphaTesting()) {
  97997. defines.push("#define ALPHATEST");
  97998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97999. attribs.push(BABYLON.VertexBuffer.UVKind);
  98000. defines.push("#define UV1");
  98001. }
  98002. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  98003. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98004. defines.push("#define UV2");
  98005. }
  98006. }
  98007. //Logarithmic depth
  98008. if (material.useLogarithmicDepth) {
  98009. defines.push("#define LOGARITHMICDEPTH");
  98010. }
  98011. }
  98012. // Bones
  98013. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  98014. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  98015. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  98016. if (mesh.numBoneInfluencers > 4) {
  98017. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  98018. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  98019. }
  98020. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  98021. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  98022. }
  98023. else {
  98024. defines.push("#define NUM_BONE_INFLUENCERS 0");
  98025. }
  98026. // Instances
  98027. if (useInstances) {
  98028. defines.push("#define INSTANCES");
  98029. attribs.push("world0");
  98030. attribs.push("world1");
  98031. attribs.push("world2");
  98032. attribs.push("world3");
  98033. }
  98034. // Get correct effect
  98035. var join = defines.join("\n");
  98036. if (this._cachedDefines !== join) {
  98037. this._cachedDefines = join;
  98038. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  98039. }
  98040. return this._effect.isReady();
  98041. };
  98042. return OutlineRenderer;
  98043. }());
  98044. BABYLON.OutlineRenderer = OutlineRenderer;
  98045. })(BABYLON || (BABYLON = {}));
  98046. //# sourceMappingURL=babylon.outlineRenderer.js.map
  98047. var BABYLON;
  98048. (function (BABYLON) {
  98049. var FaceAdjacencies = /** @class */ (function () {
  98050. function FaceAdjacencies() {
  98051. this.edges = new Array();
  98052. this.edgesConnectedCount = 0;
  98053. }
  98054. return FaceAdjacencies;
  98055. }());
  98056. var EdgesRenderer = /** @class */ (function () {
  98057. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  98058. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  98059. if (epsilon === void 0) { epsilon = 0.95; }
  98060. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  98061. this.edgesWidthScalerForOrthographic = 1000.0;
  98062. this.edgesWidthScalerForPerspective = 50.0;
  98063. this._linesPositions = new Array();
  98064. this._linesNormals = new Array();
  98065. this._linesIndices = new Array();
  98066. this._buffers = {};
  98067. this._checkVerticesInsteadOfIndices = false;
  98068. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  98069. this.isEnabled = true;
  98070. this._source = source;
  98071. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  98072. this._epsilon = epsilon;
  98073. this._prepareRessources();
  98074. this._generateEdgesLines();
  98075. }
  98076. EdgesRenderer.prototype._prepareRessources = function () {
  98077. if (this._lineShader) {
  98078. return;
  98079. }
  98080. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  98081. attributes: ["position", "normal"],
  98082. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  98083. });
  98084. this._lineShader.disableDepthWrite = true;
  98085. this._lineShader.backFaceCulling = false;
  98086. };
  98087. /** @hidden */
  98088. EdgesRenderer.prototype._rebuild = function () {
  98089. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  98090. if (buffer) {
  98091. buffer._rebuild();
  98092. }
  98093. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  98094. if (buffer) {
  98095. buffer._rebuild();
  98096. }
  98097. var scene = this._source.getScene();
  98098. var engine = scene.getEngine();
  98099. this._ib = engine.createIndexBuffer(this._linesIndices);
  98100. };
  98101. EdgesRenderer.prototype.dispose = function () {
  98102. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  98103. if (buffer) {
  98104. buffer.dispose();
  98105. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  98106. }
  98107. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  98108. if (buffer) {
  98109. buffer.dispose();
  98110. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  98111. }
  98112. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  98113. this._lineShader.dispose();
  98114. };
  98115. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  98116. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  98117. return 0;
  98118. }
  98119. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  98120. return 1;
  98121. }
  98122. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  98123. return 2;
  98124. }
  98125. return -1;
  98126. };
  98127. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  98128. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  98129. return 0;
  98130. }
  98131. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  98132. return 1;
  98133. }
  98134. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  98135. return 2;
  98136. }
  98137. return -1;
  98138. };
  98139. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  98140. var needToCreateLine;
  98141. if (edge === undefined) {
  98142. needToCreateLine = true;
  98143. }
  98144. else {
  98145. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  98146. needToCreateLine = dotProduct < this._epsilon;
  98147. }
  98148. if (needToCreateLine) {
  98149. var offset = this._linesPositions.length / 3;
  98150. var normal = p0.subtract(p1);
  98151. normal.normalize();
  98152. // Positions
  98153. this._linesPositions.push(p0.x);
  98154. this._linesPositions.push(p0.y);
  98155. this._linesPositions.push(p0.z);
  98156. this._linesPositions.push(p0.x);
  98157. this._linesPositions.push(p0.y);
  98158. this._linesPositions.push(p0.z);
  98159. this._linesPositions.push(p1.x);
  98160. this._linesPositions.push(p1.y);
  98161. this._linesPositions.push(p1.z);
  98162. this._linesPositions.push(p1.x);
  98163. this._linesPositions.push(p1.y);
  98164. this._linesPositions.push(p1.z);
  98165. // Normals
  98166. this._linesNormals.push(p1.x);
  98167. this._linesNormals.push(p1.y);
  98168. this._linesNormals.push(p1.z);
  98169. this._linesNormals.push(-1);
  98170. this._linesNormals.push(p1.x);
  98171. this._linesNormals.push(p1.y);
  98172. this._linesNormals.push(p1.z);
  98173. this._linesNormals.push(1);
  98174. this._linesNormals.push(p0.x);
  98175. this._linesNormals.push(p0.y);
  98176. this._linesNormals.push(p0.z);
  98177. this._linesNormals.push(-1);
  98178. this._linesNormals.push(p0.x);
  98179. this._linesNormals.push(p0.y);
  98180. this._linesNormals.push(p0.z);
  98181. this._linesNormals.push(1);
  98182. // Indices
  98183. this._linesIndices.push(offset);
  98184. this._linesIndices.push(offset + 1);
  98185. this._linesIndices.push(offset + 2);
  98186. this._linesIndices.push(offset);
  98187. this._linesIndices.push(offset + 2);
  98188. this._linesIndices.push(offset + 3);
  98189. }
  98190. };
  98191. EdgesRenderer.prototype._generateEdgesLines = function () {
  98192. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  98193. var indices = this._source.getIndices();
  98194. if (!indices || !positions) {
  98195. return;
  98196. }
  98197. // First let's find adjacencies
  98198. var adjacencies = new Array();
  98199. var faceNormals = new Array();
  98200. var index;
  98201. var faceAdjacencies;
  98202. // Prepare faces
  98203. for (index = 0; index < indices.length; index += 3) {
  98204. faceAdjacencies = new FaceAdjacencies();
  98205. var p0Index = indices[index];
  98206. var p1Index = indices[index + 1];
  98207. var p2Index = indices[index + 2];
  98208. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  98209. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  98210. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  98211. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  98212. faceNormal.normalize();
  98213. faceNormals.push(faceNormal);
  98214. adjacencies.push(faceAdjacencies);
  98215. }
  98216. // Scan
  98217. for (index = 0; index < adjacencies.length; index++) {
  98218. faceAdjacencies = adjacencies[index];
  98219. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  98220. var otherFaceAdjacencies = adjacencies[otherIndex];
  98221. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  98222. break;
  98223. }
  98224. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  98225. continue;
  98226. }
  98227. var otherP0 = indices[otherIndex * 3];
  98228. var otherP1 = indices[otherIndex * 3 + 1];
  98229. var otherP2 = indices[otherIndex * 3 + 2];
  98230. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  98231. var otherEdgeIndex = 0;
  98232. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  98233. continue;
  98234. }
  98235. switch (edgeIndex) {
  98236. case 0:
  98237. if (this._checkVerticesInsteadOfIndices) {
  98238. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  98239. }
  98240. else {
  98241. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  98242. }
  98243. break;
  98244. case 1:
  98245. if (this._checkVerticesInsteadOfIndices) {
  98246. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  98247. }
  98248. else {
  98249. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  98250. }
  98251. break;
  98252. case 2:
  98253. if (this._checkVerticesInsteadOfIndices) {
  98254. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  98255. }
  98256. else {
  98257. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  98258. }
  98259. break;
  98260. }
  98261. if (otherEdgeIndex === -1) {
  98262. continue;
  98263. }
  98264. faceAdjacencies.edges[edgeIndex] = otherIndex;
  98265. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  98266. faceAdjacencies.edgesConnectedCount++;
  98267. otherFaceAdjacencies.edgesConnectedCount++;
  98268. if (faceAdjacencies.edgesConnectedCount === 3) {
  98269. break;
  98270. }
  98271. }
  98272. }
  98273. }
  98274. // Create lines
  98275. for (index = 0; index < adjacencies.length; index++) {
  98276. // 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
  98277. var current = adjacencies[index];
  98278. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  98279. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  98280. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  98281. }
  98282. // Merge into a single mesh
  98283. var engine = this._source.getScene().getEngine();
  98284. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  98285. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  98286. this._ib = engine.createIndexBuffer(this._linesIndices);
  98287. this._indicesCount = this._linesIndices.length;
  98288. };
  98289. EdgesRenderer.prototype.render = function () {
  98290. var scene = this._source.getScene();
  98291. if (!this._lineShader.isReady() || !scene.activeCamera) {
  98292. return;
  98293. }
  98294. var engine = scene.getEngine();
  98295. this._lineShader._preBind();
  98296. // VBOs
  98297. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  98298. scene.resetCachedMaterial();
  98299. this._lineShader.setColor4("color", this._source.edgesColor);
  98300. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  98301. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  98302. }
  98303. else {
  98304. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  98305. }
  98306. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  98307. this._lineShader.bind(this._source.getWorldMatrix());
  98308. // Draw order
  98309. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  98310. this._lineShader.unbind();
  98311. engine.setDepthWrite(true);
  98312. };
  98313. return EdgesRenderer;
  98314. }());
  98315. BABYLON.EdgesRenderer = EdgesRenderer;
  98316. })(BABYLON || (BABYLON = {}));
  98317. //# sourceMappingURL=babylon.edgesRenderer.js.map
  98318. var BABYLON;
  98319. (function (BABYLON) {
  98320. // Adds the parser to the scene parsers.
  98321. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  98322. if (parsedData.effectLayers) {
  98323. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  98324. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  98325. container.effectLayers.push(effectLayer);
  98326. }
  98327. }
  98328. });
  98329. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  98330. var index = this.effectLayers.indexOf(toRemove);
  98331. if (index !== -1) {
  98332. this.effectLayers.splice(index, 1);
  98333. }
  98334. return index;
  98335. };
  98336. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  98337. this.effectLayers.push(newEffectLayer);
  98338. };
  98339. /**
  98340. * Defines the layer scene component responsible to manage any effect layers
  98341. * in a given scene.
  98342. */
  98343. var EffectLayerSceneComponent = /** @class */ (function () {
  98344. /**
  98345. * Creates a new instance of the component for the given scene
  98346. * @param scene Defines the scene to register the component in
  98347. */
  98348. function EffectLayerSceneComponent(scene) {
  98349. /**
  98350. * The component name helpfull to identify the component in the list of scene components.
  98351. */
  98352. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  98353. this._renderEffects = false;
  98354. this._needStencil = false;
  98355. this._previousStencilState = false;
  98356. this.scene = scene;
  98357. this._engine = scene.getEngine();
  98358. scene.effectLayers = new Array();
  98359. }
  98360. /**
  98361. * Registers the component in a given scene
  98362. */
  98363. EffectLayerSceneComponent.prototype.register = function () {
  98364. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  98365. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  98366. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  98367. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  98368. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  98369. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  98370. };
  98371. /**
  98372. * Rebuilds the elements related to this component in case of
  98373. * context lost for instance.
  98374. */
  98375. EffectLayerSceneComponent.prototype.rebuild = function () {
  98376. var layers = this.scene.effectLayers;
  98377. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  98378. var effectLayer = layers_1[_i];
  98379. effectLayer._rebuild();
  98380. }
  98381. };
  98382. /**
  98383. * Serializes the component data to the specified json object
  98384. * @param serializationObject The object to serialize to
  98385. */
  98386. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  98387. // Effect layers
  98388. serializationObject.effectLayers = [];
  98389. var layers = this.scene.effectLayers;
  98390. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  98391. var effectLayer = layers_2[_i];
  98392. if (effectLayer.serialize) {
  98393. serializationObject.effectLayers.push(effectLayer.serialize());
  98394. }
  98395. }
  98396. };
  98397. /**
  98398. * Adds all the element from the container to the scene
  98399. * @param container the container holding the elements
  98400. */
  98401. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  98402. var _this = this;
  98403. if (!container.effectLayers) {
  98404. return;
  98405. }
  98406. container.effectLayers.forEach(function (o) {
  98407. _this.scene.addEffectLayer(o);
  98408. });
  98409. };
  98410. /**
  98411. * Removes all the elements in the container from the scene
  98412. * @param container contains the elements to remove
  98413. */
  98414. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  98415. var _this = this;
  98416. if (!container.effectLayers) {
  98417. return;
  98418. }
  98419. container.effectLayers.forEach(function (o) {
  98420. _this.scene.removeEffectLayer(o);
  98421. });
  98422. };
  98423. /**
  98424. * Disposes the component and the associated ressources.
  98425. */
  98426. EffectLayerSceneComponent.prototype.dispose = function () {
  98427. var layers = this.scene.effectLayers;
  98428. while (layers.length) {
  98429. layers[0].dispose();
  98430. }
  98431. };
  98432. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  98433. var layers = this.scene.effectLayers;
  98434. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  98435. var layer = layers_3[_i];
  98436. if (!layer.hasMesh(mesh)) {
  98437. continue;
  98438. }
  98439. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  98440. var subMesh = _b[_a];
  98441. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  98442. return false;
  98443. }
  98444. }
  98445. }
  98446. return true;
  98447. };
  98448. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  98449. this._renderEffects = false;
  98450. this._needStencil = false;
  98451. var layers = this.scene.effectLayers;
  98452. if (layers && layers.length > 0) {
  98453. this._previousStencilState = this._engine.getStencilBuffer();
  98454. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  98455. var effectLayer = layers_4[_i];
  98456. if (effectLayer.shouldRender() &&
  98457. (!effectLayer.camera ||
  98458. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  98459. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  98460. this._renderEffects = true;
  98461. this._needStencil = this._needStencil || effectLayer.needStencil();
  98462. var renderTarget = effectLayer._mainTexture;
  98463. if (renderTarget._shouldRender()) {
  98464. this.scene.incrementRenderId();
  98465. renderTarget.render(false, false);
  98466. }
  98467. }
  98468. }
  98469. this.scene.incrementRenderId();
  98470. }
  98471. };
  98472. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  98473. // Activate effect Layer stencil
  98474. if (this._needStencil) {
  98475. this._engine.setStencilBuffer(true);
  98476. }
  98477. };
  98478. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  98479. // Restore effect Layer stencil
  98480. if (this._needStencil) {
  98481. this._engine.setStencilBuffer(this._previousStencilState);
  98482. }
  98483. };
  98484. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  98485. if (this._renderEffects) {
  98486. this._engine.setDepthBuffer(false);
  98487. var layers = this.scene.effectLayers;
  98488. for (var i = 0; i < layers.length; i++) {
  98489. var effectLayer = layers[i];
  98490. if (effectLayer.renderingGroupId === renderingGroupId) {
  98491. if (effectLayer.shouldRender()) {
  98492. effectLayer.render();
  98493. }
  98494. }
  98495. }
  98496. this._engine.setDepthBuffer(true);
  98497. }
  98498. };
  98499. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  98500. if (this._renderEffects) {
  98501. this._draw(-1);
  98502. }
  98503. };
  98504. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  98505. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  98506. this._draw(index);
  98507. }
  98508. };
  98509. return EffectLayerSceneComponent;
  98510. }());
  98511. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  98512. })(BABYLON || (BABYLON = {}));
  98513. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  98514. var __assign = (this && this.__assign) || Object.assign || function(t) {
  98515. for (var s, i = 1, n = arguments.length; i < n; i++) {
  98516. s = arguments[i];
  98517. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  98518. t[p] = s[p];
  98519. }
  98520. return t;
  98521. };
  98522. var BABYLON;
  98523. (function (BABYLON) {
  98524. /**
  98525. * The effect layer Helps adding post process effect blended with the main pass.
  98526. *
  98527. * This can be for instance use to generate glow or higlight effects on the scene.
  98528. *
  98529. * The effect layer class can not be used directly and is intented to inherited from to be
  98530. * customized per effects.
  98531. */
  98532. var EffectLayer = /** @class */ (function () {
  98533. /**
  98534. * Instantiates a new effect Layer and references it in the scene.
  98535. * @param name The name of the layer
  98536. * @param scene The scene to use the layer in
  98537. */
  98538. function EffectLayer(
  98539. /** The Friendly of the effect in the scene */
  98540. name, scene) {
  98541. this._vertexBuffers = {};
  98542. this._maxSize = 0;
  98543. this._mainTextureDesiredSize = { width: 0, height: 0 };
  98544. this._shouldRender = true;
  98545. this._postProcesses = [];
  98546. this._textures = [];
  98547. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  98548. /**
  98549. * The clear color of the texture used to generate the glow map.
  98550. */
  98551. this.neutralColor = new BABYLON.Color4();
  98552. /**
  98553. * Specifies wether the highlight layer is enabled or not.
  98554. */
  98555. this.isEnabled = true;
  98556. /**
  98557. * An event triggered when the effect layer has been disposed.
  98558. */
  98559. this.onDisposeObservable = new BABYLON.Observable();
  98560. /**
  98561. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  98562. */
  98563. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  98564. /**
  98565. * An event triggered when the generated texture is being merged in the scene.
  98566. */
  98567. this.onBeforeComposeObservable = new BABYLON.Observable();
  98568. /**
  98569. * An event triggered when the generated texture has been merged in the scene.
  98570. */
  98571. this.onAfterComposeObservable = new BABYLON.Observable();
  98572. /**
  98573. * An event triggered when the efffect layer changes its size.
  98574. */
  98575. this.onSizeChangedObservable = new BABYLON.Observable();
  98576. this.name = name;
  98577. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98578. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  98579. if (!component) {
  98580. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  98581. this._scene._addComponent(component);
  98582. }
  98583. this._engine = this._scene.getEngine();
  98584. this._maxSize = this._engine.getCaps().maxTextureSize;
  98585. this._scene.effectLayers.push(this);
  98586. // Generate Buffers
  98587. this._generateIndexBuffer();
  98588. this._genrateVertexBuffer();
  98589. }
  98590. Object.defineProperty(EffectLayer.prototype, "camera", {
  98591. /**
  98592. * Gets the camera attached to the layer.
  98593. */
  98594. get: function () {
  98595. return this._effectLayerOptions.camera;
  98596. },
  98597. enumerable: true,
  98598. configurable: true
  98599. });
  98600. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  98601. /**
  98602. * Gets the rendering group id the layer should render in.
  98603. */
  98604. get: function () {
  98605. return this._effectLayerOptions.renderingGroupId;
  98606. },
  98607. enumerable: true,
  98608. configurable: true
  98609. });
  98610. /**
  98611. * Initializes the effect layer with the required options.
  98612. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  98613. */
  98614. EffectLayer.prototype._init = function (options) {
  98615. // Adapt options
  98616. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  98617. this._setMainTextureSize();
  98618. this._createMainTexture();
  98619. this._createTextureAndPostProcesses();
  98620. this._mergeEffect = this._createMergeEffect();
  98621. };
  98622. /**
  98623. * Generates the index buffer of the full screen quad blending to the main canvas.
  98624. */
  98625. EffectLayer.prototype._generateIndexBuffer = function () {
  98626. // Indices
  98627. var indices = [];
  98628. indices.push(0);
  98629. indices.push(1);
  98630. indices.push(2);
  98631. indices.push(0);
  98632. indices.push(2);
  98633. indices.push(3);
  98634. this._indexBuffer = this._engine.createIndexBuffer(indices);
  98635. };
  98636. /**
  98637. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  98638. */
  98639. EffectLayer.prototype._genrateVertexBuffer = function () {
  98640. // VBO
  98641. var vertices = [];
  98642. vertices.push(1, 1);
  98643. vertices.push(-1, 1);
  98644. vertices.push(-1, -1);
  98645. vertices.push(1, -1);
  98646. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  98647. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  98648. };
  98649. /**
  98650. * Sets the main texture desired size which is the closest power of two
  98651. * of the engine canvas size.
  98652. */
  98653. EffectLayer.prototype._setMainTextureSize = function () {
  98654. if (this._effectLayerOptions.mainTextureFixedSize) {
  98655. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  98656. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  98657. }
  98658. else {
  98659. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  98660. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  98661. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  98662. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  98663. }
  98664. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  98665. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  98666. };
  98667. /**
  98668. * Creates the main texture for the effect layer.
  98669. */
  98670. EffectLayer.prototype._createMainTexture = function () {
  98671. var _this = this;
  98672. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  98673. width: this._mainTextureDesiredSize.width,
  98674. height: this._mainTextureDesiredSize.height
  98675. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  98676. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  98677. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98678. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98679. this._mainTexture.anisotropicFilteringLevel = 1;
  98680. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98681. this._mainTexture.renderParticles = false;
  98682. this._mainTexture.renderList = null;
  98683. this._mainTexture.ignoreCameraViewport = true;
  98684. // Custom render function
  98685. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  98686. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  98687. var index;
  98688. var engine = _this._scene.getEngine();
  98689. if (depthOnlySubMeshes.length) {
  98690. engine.setColorWrite(false);
  98691. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  98692. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  98693. }
  98694. engine.setColorWrite(true);
  98695. }
  98696. for (index = 0; index < opaqueSubMeshes.length; index++) {
  98697. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  98698. }
  98699. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  98700. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  98701. }
  98702. for (index = 0; index < transparentSubMeshes.length; index++) {
  98703. _this._renderSubMesh(transparentSubMeshes.data[index]);
  98704. }
  98705. };
  98706. this._mainTexture.onClearObservable.add(function (engine) {
  98707. engine.clear(_this.neutralColor, true, true, true);
  98708. });
  98709. };
  98710. /**
  98711. * Checks for the readiness of the element composing the layer.
  98712. * @param subMesh the mesh to check for
  98713. * @param useInstances specify wether or not to use instances to render the mesh
  98714. * @param emissiveTexture the associated emissive texture used to generate the glow
  98715. * @return true if ready otherwise, false
  98716. */
  98717. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  98718. var material = subMesh.getMaterial();
  98719. if (!material) {
  98720. return false;
  98721. }
  98722. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  98723. return false;
  98724. }
  98725. var defines = [];
  98726. var attribs = [BABYLON.VertexBuffer.PositionKind];
  98727. var mesh = subMesh.getMesh();
  98728. var uv1 = false;
  98729. var uv2 = false;
  98730. // Alpha test
  98731. if (material && material.needAlphaTesting()) {
  98732. var alphaTexture = material.getAlphaTestTexture();
  98733. if (alphaTexture) {
  98734. defines.push("#define ALPHATEST");
  98735. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  98736. alphaTexture.coordinatesIndex === 1) {
  98737. defines.push("#define DIFFUSEUV2");
  98738. uv2 = true;
  98739. }
  98740. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  98741. defines.push("#define DIFFUSEUV1");
  98742. uv1 = true;
  98743. }
  98744. }
  98745. }
  98746. // Emissive
  98747. if (emissiveTexture) {
  98748. defines.push("#define EMISSIVE");
  98749. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  98750. emissiveTexture.coordinatesIndex === 1) {
  98751. defines.push("#define EMISSIVEUV2");
  98752. uv2 = true;
  98753. }
  98754. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  98755. defines.push("#define EMISSIVEUV1");
  98756. uv1 = true;
  98757. }
  98758. }
  98759. if (uv1) {
  98760. attribs.push(BABYLON.VertexBuffer.UVKind);
  98761. defines.push("#define UV1");
  98762. }
  98763. if (uv2) {
  98764. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98765. defines.push("#define UV2");
  98766. }
  98767. // Bones
  98768. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  98769. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  98770. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  98771. if (mesh.numBoneInfluencers > 4) {
  98772. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  98773. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  98774. }
  98775. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  98776. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  98777. }
  98778. else {
  98779. defines.push("#define NUM_BONE_INFLUENCERS 0");
  98780. }
  98781. // Morph targets
  98782. var manager = mesh.morphTargetManager;
  98783. var morphInfluencers = 0;
  98784. if (manager) {
  98785. if (manager.numInfluencers > 0) {
  98786. defines.push("#define MORPHTARGETS");
  98787. morphInfluencers = manager.numInfluencers;
  98788. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  98789. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  98790. }
  98791. }
  98792. // Instances
  98793. if (useInstances) {
  98794. defines.push("#define INSTANCES");
  98795. attribs.push("world0");
  98796. attribs.push("world1");
  98797. attribs.push("world2");
  98798. attribs.push("world3");
  98799. }
  98800. // Get correct effect
  98801. var join = defines.join("\n");
  98802. if (this._cachedDefines !== join) {
  98803. this._cachedDefines = join;
  98804. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  98805. }
  98806. return this._effectLayerMapGenerationEffect.isReady();
  98807. };
  98808. /**
  98809. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  98810. */
  98811. EffectLayer.prototype.render = function () {
  98812. var currentEffect = this._mergeEffect;
  98813. // Check
  98814. if (!currentEffect.isReady())
  98815. return;
  98816. for (var i = 0; i < this._postProcesses.length; i++) {
  98817. if (!this._postProcesses[i].isReady()) {
  98818. return;
  98819. }
  98820. }
  98821. var engine = this._scene.getEngine();
  98822. this.onBeforeComposeObservable.notifyObservers(this);
  98823. // Render
  98824. engine.enableEffect(currentEffect);
  98825. engine.setState(false);
  98826. // VBOs
  98827. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  98828. // Cache
  98829. var previousAlphaMode = engine.getAlphaMode();
  98830. // Go Blend.
  98831. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  98832. // Blends the map on the main canvas.
  98833. this._internalRender(currentEffect);
  98834. // Restore Alpha
  98835. engine.setAlphaMode(previousAlphaMode);
  98836. this.onAfterComposeObservable.notifyObservers(this);
  98837. // Handle size changes.
  98838. var size = this._mainTexture.getSize();
  98839. this._setMainTextureSize();
  98840. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  98841. // Recreate RTT and post processes on size change.
  98842. this.onSizeChangedObservable.notifyObservers(this);
  98843. this._disposeTextureAndPostProcesses();
  98844. this._createMainTexture();
  98845. this._createTextureAndPostProcesses();
  98846. }
  98847. };
  98848. /**
  98849. * Determine if a given mesh will be used in the current effect.
  98850. * @param mesh mesh to test
  98851. * @returns true if the mesh will be used
  98852. */
  98853. EffectLayer.prototype.hasMesh = function (mesh) {
  98854. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  98855. return true;
  98856. }
  98857. return false;
  98858. };
  98859. /**
  98860. * Returns true if the layer contains information to display, otherwise false.
  98861. * @returns true if the glow layer should be rendered
  98862. */
  98863. EffectLayer.prototype.shouldRender = function () {
  98864. return this.isEnabled && this._shouldRender;
  98865. };
  98866. /**
  98867. * Returns true if the mesh should render, otherwise false.
  98868. * @param mesh The mesh to render
  98869. * @returns true if it should render otherwise false
  98870. */
  98871. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  98872. return true;
  98873. };
  98874. /**
  98875. * Returns true if the mesh should render, otherwise false.
  98876. * @param mesh The mesh to render
  98877. * @returns true if it should render otherwise false
  98878. */
  98879. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  98880. return true;
  98881. };
  98882. /**
  98883. * Renders the submesh passed in parameter to the generation map.
  98884. */
  98885. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  98886. var _this = this;
  98887. if (!this.shouldRender()) {
  98888. return;
  98889. }
  98890. var material = subMesh.getMaterial();
  98891. var mesh = subMesh.getRenderingMesh();
  98892. var scene = this._scene;
  98893. var engine = scene.getEngine();
  98894. if (!material) {
  98895. return;
  98896. }
  98897. // Do not block in blend mode.
  98898. if (material.needAlphaBlendingForMesh(mesh)) {
  98899. return;
  98900. }
  98901. // Culling
  98902. engine.setState(material.backFaceCulling);
  98903. // Managing instances
  98904. var batch = mesh._getInstancesRenderList(subMesh._id);
  98905. if (batch.mustReturn) {
  98906. return;
  98907. }
  98908. // Early Exit per mesh
  98909. if (!this._shouldRenderMesh(mesh)) {
  98910. return;
  98911. }
  98912. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  98913. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  98914. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  98915. engine.enableEffect(this._effectLayerMapGenerationEffect);
  98916. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  98917. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  98918. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  98919. // Alpha test
  98920. if (material && material.needAlphaTesting()) {
  98921. var alphaTexture = material.getAlphaTestTexture();
  98922. if (alphaTexture) {
  98923. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  98924. var textureMatrix = alphaTexture.getTextureMatrix();
  98925. if (textureMatrix) {
  98926. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  98927. }
  98928. }
  98929. }
  98930. // Glow emissive only
  98931. if (this._emissiveTextureAndColor.texture) {
  98932. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  98933. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  98934. }
  98935. // Bones
  98936. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  98937. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  98938. }
  98939. // Morph targets
  98940. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  98941. // Draw
  98942. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  98943. }
  98944. else {
  98945. // Need to reset refresh rate of the main map
  98946. this._mainTexture.resetRefreshCounter();
  98947. }
  98948. };
  98949. /**
  98950. * Rebuild the required buffers.
  98951. * @hidden Internal use only.
  98952. */
  98953. EffectLayer.prototype._rebuild = function () {
  98954. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98955. if (vb) {
  98956. vb._rebuild();
  98957. }
  98958. this._generateIndexBuffer();
  98959. };
  98960. /**
  98961. * Dispose only the render target textures and post process.
  98962. */
  98963. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  98964. this._mainTexture.dispose();
  98965. for (var i = 0; i < this._postProcesses.length; i++) {
  98966. if (this._postProcesses[i]) {
  98967. this._postProcesses[i].dispose();
  98968. }
  98969. }
  98970. this._postProcesses = [];
  98971. for (var i = 0; i < this._textures.length; i++) {
  98972. if (this._textures[i]) {
  98973. this._textures[i].dispose();
  98974. }
  98975. }
  98976. this._textures = [];
  98977. };
  98978. /**
  98979. * Dispose the highlight layer and free resources.
  98980. */
  98981. EffectLayer.prototype.dispose = function () {
  98982. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98983. if (vertexBuffer) {
  98984. vertexBuffer.dispose();
  98985. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  98986. }
  98987. if (this._indexBuffer) {
  98988. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  98989. this._indexBuffer = null;
  98990. }
  98991. // Clean textures and post processes
  98992. this._disposeTextureAndPostProcesses();
  98993. // Remove from scene
  98994. var index = this._scene.effectLayers.indexOf(this, 0);
  98995. if (index > -1) {
  98996. this._scene.effectLayers.splice(index, 1);
  98997. }
  98998. // Callback
  98999. this.onDisposeObservable.notifyObservers(this);
  99000. this.onDisposeObservable.clear();
  99001. this.onBeforeRenderMainTextureObservable.clear();
  99002. this.onBeforeComposeObservable.clear();
  99003. this.onAfterComposeObservable.clear();
  99004. this.onSizeChangedObservable.clear();
  99005. };
  99006. /**
  99007. * Gets the class name of the effect layer
  99008. * @returns the string with the class name of the effect layer
  99009. */
  99010. EffectLayer.prototype.getClassName = function () {
  99011. return "EffectLayer";
  99012. };
  99013. /**
  99014. * Creates an effect layer from parsed effect layer data
  99015. * @param parsedEffectLayer defines effect layer data
  99016. * @param scene defines the current scene
  99017. * @param rootUrl defines the root URL containing the effect layer information
  99018. * @returns a parsed effect Layer
  99019. */
  99020. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  99021. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  99022. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  99023. };
  99024. __decorate([
  99025. BABYLON.serialize()
  99026. ], EffectLayer.prototype, "name", void 0);
  99027. __decorate([
  99028. BABYLON.serializeAsColor4()
  99029. ], EffectLayer.prototype, "neutralColor", void 0);
  99030. __decorate([
  99031. BABYLON.serialize()
  99032. ], EffectLayer.prototype, "isEnabled", void 0);
  99033. __decorate([
  99034. BABYLON.serializeAsCameraReference()
  99035. ], EffectLayer.prototype, "camera", null);
  99036. __decorate([
  99037. BABYLON.serialize()
  99038. ], EffectLayer.prototype, "renderingGroupId", null);
  99039. return EffectLayer;
  99040. }());
  99041. BABYLON.EffectLayer = EffectLayer;
  99042. })(BABYLON || (BABYLON = {}));
  99043. //# sourceMappingURL=babylon.effectLayer.js.map
  99044. var BABYLON;
  99045. (function (BABYLON) {
  99046. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  99047. for (var index = 0; index < this.effectLayers.length; index++) {
  99048. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  99049. return this.effectLayers[index];
  99050. }
  99051. }
  99052. return null;
  99053. };
  99054. /**
  99055. * Special Glow Blur post process only blurring the alpha channel
  99056. * It enforces keeping the most luminous color in the color channel.
  99057. */
  99058. var GlowBlurPostProcess = /** @class */ (function (_super) {
  99059. __extends(GlowBlurPostProcess, _super);
  99060. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  99061. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  99062. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  99063. _this.direction = direction;
  99064. _this.kernel = kernel;
  99065. _this.onApplyObservable.add(function (effect) {
  99066. effect.setFloat2("screenSize", _this.width, _this.height);
  99067. effect.setVector2("direction", _this.direction);
  99068. effect.setFloat("blurWidth", _this.kernel);
  99069. });
  99070. return _this;
  99071. }
  99072. return GlowBlurPostProcess;
  99073. }(BABYLON.PostProcess));
  99074. /**
  99075. * The highlight layer Helps adding a glow effect around a mesh.
  99076. *
  99077. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  99078. * glowy meshes to your scene.
  99079. *
  99080. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  99081. */
  99082. var HighlightLayer = /** @class */ (function (_super) {
  99083. __extends(HighlightLayer, _super);
  99084. /**
  99085. * Instantiates a new highlight Layer and references it to the scene..
  99086. * @param name The name of the layer
  99087. * @param scene The scene to use the layer in
  99088. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  99089. */
  99090. function HighlightLayer(name, scene, options) {
  99091. var _this = _super.call(this, name, scene) || this;
  99092. _this.name = name;
  99093. /**
  99094. * Specifies whether or not the inner glow is ACTIVE in the layer.
  99095. */
  99096. _this.innerGlow = true;
  99097. /**
  99098. * Specifies whether or not the outer glow is ACTIVE in the layer.
  99099. */
  99100. _this.outerGlow = true;
  99101. /**
  99102. * An event triggered when the highlight layer is being blurred.
  99103. */
  99104. _this.onBeforeBlurObservable = new BABYLON.Observable();
  99105. /**
  99106. * An event triggered when the highlight layer has been blurred.
  99107. */
  99108. _this.onAfterBlurObservable = new BABYLON.Observable();
  99109. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  99110. _this._meshes = {};
  99111. _this._excludedMeshes = {};
  99112. _this.neutralColor = HighlightLayer.NeutralColor;
  99113. // Warn on stencil
  99114. if (!_this._engine.isStencilEnable) {
  99115. 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 }");
  99116. }
  99117. // Adapt options
  99118. _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);
  99119. // Initialize the layer
  99120. _this._init({
  99121. alphaBlendingMode: _this._options.alphaBlendingMode,
  99122. camera: _this._options.camera,
  99123. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  99124. mainTextureRatio: _this._options.mainTextureRatio,
  99125. renderingGroupId: _this._options.renderingGroupId
  99126. });
  99127. // Do not render as long as no meshes have been added
  99128. _this._shouldRender = false;
  99129. return _this;
  99130. }
  99131. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  99132. /**
  99133. * Gets the horizontal size of the blur.
  99134. */
  99135. get: function () {
  99136. return this._horizontalBlurPostprocess.kernel;
  99137. },
  99138. /**
  99139. * Specifies the horizontal size of the blur.
  99140. */
  99141. set: function (value) {
  99142. this._horizontalBlurPostprocess.kernel = value;
  99143. },
  99144. enumerable: true,
  99145. configurable: true
  99146. });
  99147. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  99148. /**
  99149. * Gets the vertical size of the blur.
  99150. */
  99151. get: function () {
  99152. return this._verticalBlurPostprocess.kernel;
  99153. },
  99154. /**
  99155. * Specifies the vertical size of the blur.
  99156. */
  99157. set: function (value) {
  99158. this._verticalBlurPostprocess.kernel = value;
  99159. },
  99160. enumerable: true,
  99161. configurable: true
  99162. });
  99163. /**
  99164. * Get the effect name of the layer.
  99165. * @return The effect name
  99166. */
  99167. HighlightLayer.prototype.getEffectName = function () {
  99168. return HighlightLayer.EffectName;
  99169. };
  99170. /**
  99171. * Create the merge effect. This is the shader use to blit the information back
  99172. * to the main canvas at the end of the scene rendering.
  99173. */
  99174. HighlightLayer.prototype._createMergeEffect = function () {
  99175. // Effect
  99176. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  99177. };
  99178. /**
  99179. * Creates the render target textures and post processes used in the highlight layer.
  99180. */
  99181. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  99182. var _this = this;
  99183. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  99184. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  99185. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  99186. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  99187. var textureType = 0;
  99188. if (this._engine.getCaps().textureHalfFloatRender) {
  99189. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99190. }
  99191. else {
  99192. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99193. }
  99194. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  99195. width: blurTextureWidth,
  99196. height: blurTextureHeight
  99197. }, this._scene, false, true, textureType);
  99198. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99199. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99200. this._blurTexture.anisotropicFilteringLevel = 16;
  99201. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  99202. this._blurTexture.renderParticles = false;
  99203. this._blurTexture.ignoreCameraViewport = true;
  99204. this._textures = [this._blurTexture];
  99205. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  99206. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  99207. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  99208. effect.setTexture("textureSampler", _this._mainTexture);
  99209. });
  99210. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  99211. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  99212. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  99213. });
  99214. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  99215. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  99216. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  99217. });
  99218. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  99219. }
  99220. else {
  99221. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  99222. width: blurTextureWidth,
  99223. height: blurTextureHeight
  99224. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99225. this._horizontalBlurPostprocess.width = blurTextureWidth;
  99226. this._horizontalBlurPostprocess.height = blurTextureHeight;
  99227. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  99228. effect.setTexture("textureSampler", _this._mainTexture);
  99229. });
  99230. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  99231. width: blurTextureWidth,
  99232. height: blurTextureHeight
  99233. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99234. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  99235. }
  99236. this._mainTexture.onAfterUnbindObservable.add(function () {
  99237. _this.onBeforeBlurObservable.notifyObservers(_this);
  99238. var internalTexture = _this._blurTexture.getInternalTexture();
  99239. if (internalTexture) {
  99240. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  99241. }
  99242. _this.onAfterBlurObservable.notifyObservers(_this);
  99243. });
  99244. // Prevent autoClear.
  99245. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  99246. };
  99247. /**
  99248. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  99249. */
  99250. HighlightLayer.prototype.needStencil = function () {
  99251. return true;
  99252. };
  99253. /**
  99254. * Checks for the readiness of the element composing the layer.
  99255. * @param subMesh the mesh to check for
  99256. * @param useInstances specify wether or not to use instances to render the mesh
  99257. * @param emissiveTexture the associated emissive texture used to generate the glow
  99258. * @return true if ready otherwise, false
  99259. */
  99260. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  99261. var material = subMesh.getMaterial();
  99262. var mesh = subMesh.getRenderingMesh();
  99263. if (!material || !mesh || !this._meshes) {
  99264. return false;
  99265. }
  99266. var emissiveTexture = null;
  99267. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  99268. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  99269. emissiveTexture = material.emissiveTexture;
  99270. }
  99271. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  99272. };
  99273. /**
  99274. * Implementation specific of rendering the generating effect on the main canvas.
  99275. * @param effect The effect used to render through
  99276. */
  99277. HighlightLayer.prototype._internalRender = function (effect) {
  99278. // Texture
  99279. effect.setTexture("textureSampler", this._blurTexture);
  99280. // Cache
  99281. var engine = this._engine;
  99282. var previousStencilBuffer = engine.getStencilBuffer();
  99283. var previousStencilFunction = engine.getStencilFunction();
  99284. var previousStencilMask = engine.getStencilMask();
  99285. var previousStencilOperationPass = engine.getStencilOperationPass();
  99286. var previousStencilOperationFail = engine.getStencilOperationFail();
  99287. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  99288. var previousStencilReference = engine.getStencilFunctionReference();
  99289. // Stencil operations
  99290. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  99291. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  99292. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  99293. // Draw order
  99294. engine.setStencilMask(0x00);
  99295. engine.setStencilBuffer(true);
  99296. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  99297. // 2 passes inner outer
  99298. if (this.outerGlow) {
  99299. effect.setFloat("offset", 0);
  99300. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  99301. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99302. }
  99303. if (this.innerGlow) {
  99304. effect.setFloat("offset", 1);
  99305. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  99306. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99307. }
  99308. // Restore Cache
  99309. engine.setStencilFunction(previousStencilFunction);
  99310. engine.setStencilMask(previousStencilMask);
  99311. engine.setStencilBuffer(previousStencilBuffer);
  99312. engine.setStencilOperationPass(previousStencilOperationPass);
  99313. engine.setStencilOperationFail(previousStencilOperationFail);
  99314. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  99315. engine.setStencilFunctionReference(previousStencilReference);
  99316. };
  99317. /**
  99318. * Returns true if the layer contains information to display, otherwise false.
  99319. */
  99320. HighlightLayer.prototype.shouldRender = function () {
  99321. if (_super.prototype.shouldRender.call(this)) {
  99322. return this._meshes ? true : false;
  99323. }
  99324. return false;
  99325. };
  99326. /**
  99327. * Returns true if the mesh should render, otherwise false.
  99328. * @param mesh The mesh to render
  99329. * @returns true if it should render otherwise false
  99330. */
  99331. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  99332. // Excluded Mesh
  99333. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  99334. return false;
  99335. }
  99336. ;
  99337. if (!_super.prototype.hasMesh.call(this, mesh)) {
  99338. return false;
  99339. }
  99340. return true;
  99341. };
  99342. /**
  99343. * Sets the required values for both the emissive texture and and the main color.
  99344. */
  99345. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  99346. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  99347. if (highlightLayerMesh) {
  99348. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  99349. }
  99350. else {
  99351. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  99352. }
  99353. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  99354. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  99355. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  99356. }
  99357. else {
  99358. this._emissiveTextureAndColor.texture = null;
  99359. }
  99360. };
  99361. /**
  99362. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  99363. * @param mesh The mesh to exclude from the highlight layer
  99364. */
  99365. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  99366. if (!this._excludedMeshes) {
  99367. return;
  99368. }
  99369. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  99370. if (!meshExcluded) {
  99371. this._excludedMeshes[mesh.uniqueId] = {
  99372. mesh: mesh,
  99373. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  99374. mesh.getEngine().setStencilBuffer(false);
  99375. }),
  99376. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  99377. mesh.getEngine().setStencilBuffer(true);
  99378. }),
  99379. };
  99380. }
  99381. };
  99382. /**
  99383. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  99384. * @param mesh The mesh to highlight
  99385. */
  99386. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  99387. if (!this._excludedMeshes) {
  99388. return;
  99389. }
  99390. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  99391. if (meshExcluded) {
  99392. if (meshExcluded.beforeRender) {
  99393. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  99394. }
  99395. if (meshExcluded.afterRender) {
  99396. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  99397. }
  99398. }
  99399. this._excludedMeshes[mesh.uniqueId] = null;
  99400. };
  99401. /**
  99402. * Determine if a given mesh will be highlighted by the current HighlightLayer
  99403. * @param mesh mesh to test
  99404. * @returns true if the mesh will be highlighted by the current HighlightLayer
  99405. */
  99406. HighlightLayer.prototype.hasMesh = function (mesh) {
  99407. if (!this._meshes) {
  99408. return false;
  99409. }
  99410. if (!_super.prototype.hasMesh.call(this, mesh)) {
  99411. return false;
  99412. }
  99413. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  99414. };
  99415. /**
  99416. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  99417. * @param mesh The mesh to highlight
  99418. * @param color The color of the highlight
  99419. * @param glowEmissiveOnly Extract the glow from the emissive texture
  99420. */
  99421. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  99422. var _this = this;
  99423. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  99424. if (!this._meshes) {
  99425. return;
  99426. }
  99427. var meshHighlight = this._meshes[mesh.uniqueId];
  99428. if (meshHighlight) {
  99429. meshHighlight.color = color;
  99430. }
  99431. else {
  99432. this._meshes[mesh.uniqueId] = {
  99433. mesh: mesh,
  99434. color: color,
  99435. // Lambda required for capture due to Observable this context
  99436. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  99437. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  99438. _this._defaultStencilReference(mesh);
  99439. }
  99440. else {
  99441. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  99442. }
  99443. }),
  99444. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  99445. glowEmissiveOnly: glowEmissiveOnly
  99446. };
  99447. mesh.onDisposeObservable.add(function () {
  99448. _this._disposeMesh(mesh);
  99449. });
  99450. }
  99451. this._shouldRender = true;
  99452. };
  99453. /**
  99454. * Remove a mesh from the highlight layer in order to make it stop glowing.
  99455. * @param mesh The mesh to highlight
  99456. */
  99457. HighlightLayer.prototype.removeMesh = function (mesh) {
  99458. if (!this._meshes) {
  99459. return;
  99460. }
  99461. var meshHighlight = this._meshes[mesh.uniqueId];
  99462. if (meshHighlight) {
  99463. if (meshHighlight.observerHighlight) {
  99464. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  99465. }
  99466. if (meshHighlight.observerDefault) {
  99467. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  99468. }
  99469. delete this._meshes[mesh.uniqueId];
  99470. }
  99471. this._shouldRender = false;
  99472. for (var meshHighlightToCheck in this._meshes) {
  99473. if (this._meshes[meshHighlightToCheck]) {
  99474. this._shouldRender = true;
  99475. break;
  99476. }
  99477. }
  99478. };
  99479. /**
  99480. * Force the stencil to the normal expected value for none glowing parts
  99481. */
  99482. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  99483. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  99484. };
  99485. /**
  99486. * Free any resources and references associated to a mesh.
  99487. * Internal use
  99488. * @param mesh The mesh to free.
  99489. * @hidden
  99490. */
  99491. HighlightLayer.prototype._disposeMesh = function (mesh) {
  99492. this.removeMesh(mesh);
  99493. this.removeExcludedMesh(mesh);
  99494. };
  99495. /**
  99496. * Dispose the highlight layer and free resources.
  99497. */
  99498. HighlightLayer.prototype.dispose = function () {
  99499. if (this._meshes) {
  99500. // Clean mesh references
  99501. for (var id in this._meshes) {
  99502. var meshHighlight = this._meshes[id];
  99503. if (meshHighlight && meshHighlight.mesh) {
  99504. if (meshHighlight.observerHighlight) {
  99505. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  99506. }
  99507. if (meshHighlight.observerDefault) {
  99508. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  99509. }
  99510. }
  99511. }
  99512. this._meshes = null;
  99513. }
  99514. if (this._excludedMeshes) {
  99515. for (var id in this._excludedMeshes) {
  99516. var meshHighlight = this._excludedMeshes[id];
  99517. if (meshHighlight) {
  99518. if (meshHighlight.beforeRender) {
  99519. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  99520. }
  99521. if (meshHighlight.afterRender) {
  99522. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  99523. }
  99524. }
  99525. }
  99526. this._excludedMeshes = null;
  99527. }
  99528. _super.prototype.dispose.call(this);
  99529. };
  99530. /**
  99531. * Gets the class name of the effect layer
  99532. * @returns the string with the class name of the effect layer
  99533. */
  99534. HighlightLayer.prototype.getClassName = function () {
  99535. return "HighlightLayer";
  99536. };
  99537. /**
  99538. * Serializes this Highlight layer
  99539. * @returns a serialized Highlight layer object
  99540. */
  99541. HighlightLayer.prototype.serialize = function () {
  99542. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99543. serializationObject.customType = "BABYLON.HighlightLayer";
  99544. // Highlighted meshes
  99545. serializationObject.meshes = [];
  99546. if (this._meshes) {
  99547. for (var m in this._meshes) {
  99548. var mesh = this._meshes[m];
  99549. if (mesh) {
  99550. serializationObject.meshes.push({
  99551. glowEmissiveOnly: mesh.glowEmissiveOnly,
  99552. color: mesh.color.asArray(),
  99553. meshId: mesh.mesh.id
  99554. });
  99555. }
  99556. }
  99557. }
  99558. // Excluded meshes
  99559. serializationObject.excludedMeshes = [];
  99560. if (this._excludedMeshes) {
  99561. for (var e in this._excludedMeshes) {
  99562. var excludedMesh = this._excludedMeshes[e];
  99563. if (excludedMesh) {
  99564. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  99565. }
  99566. }
  99567. }
  99568. return serializationObject;
  99569. };
  99570. /**
  99571. * Creates a Highlight layer from parsed Highlight layer data
  99572. * @param parsedHightlightLayer defines the Highlight layer data
  99573. * @param scene defines the current scene
  99574. * @param rootUrl defines the root URL containing the Highlight layer information
  99575. * @returns a parsed Highlight layer
  99576. */
  99577. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  99578. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  99579. var index;
  99580. // Excluded meshes
  99581. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  99582. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  99583. if (mesh) {
  99584. hl.addExcludedMesh(mesh);
  99585. }
  99586. }
  99587. // Included meshes
  99588. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  99589. var highlightedMesh = parsedHightlightLayer.meshes[index];
  99590. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  99591. if (mesh) {
  99592. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  99593. }
  99594. }
  99595. return hl;
  99596. };
  99597. /**
  99598. * Effect Name of the highlight layer.
  99599. */
  99600. HighlightLayer.EffectName = "HighlightLayer";
  99601. /**
  99602. * The neutral color used during the preparation of the glow effect.
  99603. * This is black by default as the blend operation is a blend operation.
  99604. */
  99605. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  99606. /**
  99607. * Stencil value used for glowing meshes.
  99608. */
  99609. HighlightLayer.GlowingMeshStencilReference = 0x02;
  99610. /**
  99611. * Stencil value used for the other meshes in the scene.
  99612. */
  99613. HighlightLayer.NormalMeshStencilReference = 0x01;
  99614. __decorate([
  99615. BABYLON.serialize()
  99616. ], HighlightLayer.prototype, "innerGlow", void 0);
  99617. __decorate([
  99618. BABYLON.serialize()
  99619. ], HighlightLayer.prototype, "outerGlow", void 0);
  99620. __decorate([
  99621. BABYLON.serialize()
  99622. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  99623. __decorate([
  99624. BABYLON.serialize()
  99625. ], HighlightLayer.prototype, "blurVerticalSize", null);
  99626. __decorate([
  99627. BABYLON.serialize("options")
  99628. ], HighlightLayer.prototype, "_options", void 0);
  99629. return HighlightLayer;
  99630. }(BABYLON.EffectLayer));
  99631. BABYLON.HighlightLayer = HighlightLayer;
  99632. })(BABYLON || (BABYLON = {}));
  99633. //# sourceMappingURL=babylon.highlightLayer.js.map
  99634. var BABYLON;
  99635. (function (BABYLON) {
  99636. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  99637. for (var index = 0; index < this.effectLayers.length; index++) {
  99638. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  99639. return this.effectLayers[index];
  99640. }
  99641. }
  99642. return null;
  99643. };
  99644. /**
  99645. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  99646. *
  99647. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  99648. * glowy meshes to your scene.
  99649. *
  99650. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  99651. */
  99652. var GlowLayer = /** @class */ (function (_super) {
  99653. __extends(GlowLayer, _super);
  99654. /**
  99655. * Instantiates a new glow Layer and references it to the scene.
  99656. * @param name The name of the layer
  99657. * @param scene The scene to use the layer in
  99658. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  99659. */
  99660. function GlowLayer(name, scene, options) {
  99661. var _this = _super.call(this, name, scene) || this;
  99662. _this._intensity = 1.0;
  99663. _this._includedOnlyMeshes = [];
  99664. _this._excludedMeshes = [];
  99665. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  99666. // Adapt options
  99667. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  99668. // Initialize the layer
  99669. _this._init({
  99670. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  99671. camera: _this._options.camera,
  99672. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  99673. mainTextureRatio: _this._options.mainTextureRatio,
  99674. renderingGroupId: _this._options.renderingGroupId
  99675. });
  99676. return _this;
  99677. }
  99678. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  99679. /**
  99680. * Gets the kernel size of the blur.
  99681. */
  99682. get: function () {
  99683. return this._horizontalBlurPostprocess1.kernel;
  99684. },
  99685. /**
  99686. * Sets the kernel size of the blur.
  99687. */
  99688. set: function (value) {
  99689. this._horizontalBlurPostprocess1.kernel = value;
  99690. this._verticalBlurPostprocess1.kernel = value;
  99691. this._horizontalBlurPostprocess2.kernel = value;
  99692. this._verticalBlurPostprocess2.kernel = value;
  99693. },
  99694. enumerable: true,
  99695. configurable: true
  99696. });
  99697. Object.defineProperty(GlowLayer.prototype, "intensity", {
  99698. /**
  99699. * Gets the glow intensity.
  99700. */
  99701. get: function () {
  99702. return this._intensity;
  99703. },
  99704. /**
  99705. * Sets the glow intensity.
  99706. */
  99707. set: function (value) {
  99708. this._intensity = value;
  99709. },
  99710. enumerable: true,
  99711. configurable: true
  99712. });
  99713. /**
  99714. * Get the effect name of the layer.
  99715. * @return The effect name
  99716. */
  99717. GlowLayer.prototype.getEffectName = function () {
  99718. return GlowLayer.EffectName;
  99719. };
  99720. /**
  99721. * Create the merge effect. This is the shader use to blit the information back
  99722. * to the main canvas at the end of the scene rendering.
  99723. */
  99724. GlowLayer.prototype._createMergeEffect = function () {
  99725. // Effect
  99726. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  99727. };
  99728. /**
  99729. * Creates the render target textures and post processes used in the glow layer.
  99730. */
  99731. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  99732. var _this = this;
  99733. var blurTextureWidth = this._mainTextureDesiredSize.width;
  99734. var blurTextureHeight = this._mainTextureDesiredSize.height;
  99735. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  99736. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  99737. var textureType = 0;
  99738. if (this._engine.getCaps().textureHalfFloatRender) {
  99739. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99740. }
  99741. else {
  99742. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99743. }
  99744. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  99745. width: blurTextureWidth,
  99746. height: blurTextureHeight
  99747. }, this._scene, false, true, textureType);
  99748. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99749. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99750. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99751. this._blurTexture1.renderParticles = false;
  99752. this._blurTexture1.ignoreCameraViewport = true;
  99753. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  99754. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  99755. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  99756. width: blurTextureWidth2,
  99757. height: blurTextureHeight2
  99758. }, this._scene, false, true, textureType);
  99759. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99760. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99761. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99762. this._blurTexture2.renderParticles = false;
  99763. this._blurTexture2.ignoreCameraViewport = true;
  99764. this._textures = [this._blurTexture1, this._blurTexture2];
  99765. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  99766. width: blurTextureWidth,
  99767. height: blurTextureHeight
  99768. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99769. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  99770. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  99771. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  99772. effect.setTexture("textureSampler", _this._mainTexture);
  99773. });
  99774. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  99775. width: blurTextureWidth,
  99776. height: blurTextureHeight
  99777. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99778. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  99779. width: blurTextureWidth2,
  99780. height: blurTextureHeight2
  99781. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99782. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  99783. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  99784. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  99785. effect.setTexture("textureSampler", _this._blurTexture1);
  99786. });
  99787. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  99788. width: blurTextureWidth2,
  99789. height: blurTextureHeight2
  99790. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99791. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  99792. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  99793. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  99794. this._mainTexture.samples = this._options.mainTextureSamples;
  99795. this._mainTexture.onAfterUnbindObservable.add(function () {
  99796. var internalTexture = _this._blurTexture1.getInternalTexture();
  99797. if (internalTexture) {
  99798. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  99799. internalTexture = _this._blurTexture2.getInternalTexture();
  99800. if (internalTexture) {
  99801. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  99802. }
  99803. }
  99804. });
  99805. // Prevent autoClear.
  99806. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  99807. };
  99808. /**
  99809. * Checks for the readiness of the element composing the layer.
  99810. * @param subMesh the mesh to check for
  99811. * @param useInstances specify wether or not to use instances to render the mesh
  99812. * @param emissiveTexture the associated emissive texture used to generate the glow
  99813. * @return true if ready otherwise, false
  99814. */
  99815. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  99816. var material = subMesh.getMaterial();
  99817. var mesh = subMesh.getRenderingMesh();
  99818. if (!material || !mesh) {
  99819. return false;
  99820. }
  99821. var emissiveTexture = material.emissiveTexture;
  99822. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  99823. };
  99824. /**
  99825. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  99826. */
  99827. GlowLayer.prototype.needStencil = function () {
  99828. return false;
  99829. };
  99830. /**
  99831. * Implementation specific of rendering the generating effect on the main canvas.
  99832. * @param effect The effect used to render through
  99833. */
  99834. GlowLayer.prototype._internalRender = function (effect) {
  99835. // Texture
  99836. effect.setTexture("textureSampler", this._blurTexture1);
  99837. effect.setTexture("textureSampler2", this._blurTexture2);
  99838. effect.setFloat("offset", this._intensity);
  99839. // Cache
  99840. var engine = this._engine;
  99841. var previousStencilBuffer = engine.getStencilBuffer();
  99842. // Draw order
  99843. engine.setStencilBuffer(false);
  99844. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99845. // Draw order
  99846. engine.setStencilBuffer(previousStencilBuffer);
  99847. };
  99848. /**
  99849. * Sets the required values for both the emissive texture and and the main color.
  99850. */
  99851. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  99852. var textureLevel = 1.0;
  99853. if (this.customEmissiveTextureSelector) {
  99854. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  99855. }
  99856. else {
  99857. if (material) {
  99858. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  99859. if (this._emissiveTextureAndColor.texture) {
  99860. textureLevel = this._emissiveTextureAndColor.texture.level;
  99861. }
  99862. }
  99863. else {
  99864. this._emissiveTextureAndColor.texture = null;
  99865. }
  99866. }
  99867. if (this.customEmissiveColorSelector) {
  99868. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  99869. }
  99870. else {
  99871. if (material.emissiveColor) {
  99872. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  99873. }
  99874. else {
  99875. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  99876. }
  99877. }
  99878. };
  99879. /**
  99880. * Returns true if the mesh should render, otherwise false.
  99881. * @param mesh The mesh to render
  99882. * @returns true if it should render otherwise false
  99883. */
  99884. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  99885. return this.hasMesh(mesh);
  99886. };
  99887. /**
  99888. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  99889. * @param mesh The mesh to exclude from the glow layer
  99890. */
  99891. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  99892. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  99893. this._excludedMeshes.push(mesh.uniqueId);
  99894. }
  99895. };
  99896. /**
  99897. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  99898. * @param mesh The mesh to remove
  99899. */
  99900. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  99901. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  99902. if (index !== -1) {
  99903. this._excludedMeshes.splice(index, 1);
  99904. }
  99905. };
  99906. /**
  99907. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  99908. * @param mesh The mesh to include in the glow layer
  99909. */
  99910. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  99911. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  99912. this._includedOnlyMeshes.push(mesh.uniqueId);
  99913. }
  99914. };
  99915. /**
  99916. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  99917. * @param mesh The mesh to remove
  99918. */
  99919. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  99920. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  99921. if (index !== -1) {
  99922. this._includedOnlyMeshes.splice(index, 1);
  99923. }
  99924. };
  99925. /**
  99926. * Determine if a given mesh will be used in the glow layer
  99927. * @param mesh The mesh to test
  99928. * @returns true if the mesh will be highlighted by the current glow layer
  99929. */
  99930. GlowLayer.prototype.hasMesh = function (mesh) {
  99931. if (!_super.prototype.hasMesh.call(this, mesh)) {
  99932. return false;
  99933. }
  99934. // Included Mesh
  99935. if (this._includedOnlyMeshes.length) {
  99936. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  99937. }
  99938. ;
  99939. // Excluded Mesh
  99940. if (this._excludedMeshes.length) {
  99941. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  99942. }
  99943. ;
  99944. return true;
  99945. };
  99946. /**
  99947. * Free any resources and references associated to a mesh.
  99948. * Internal use
  99949. * @param mesh The mesh to free.
  99950. * @hidden
  99951. */
  99952. GlowLayer.prototype._disposeMesh = function (mesh) {
  99953. this.removeIncludedOnlyMesh(mesh);
  99954. this.removeExcludedMesh(mesh);
  99955. };
  99956. /**
  99957. * Gets the class name of the effect layer
  99958. * @returns the string with the class name of the effect layer
  99959. */
  99960. GlowLayer.prototype.getClassName = function () {
  99961. return "GlowLayer";
  99962. };
  99963. /**
  99964. * Serializes this glow layer
  99965. * @returns a serialized glow layer object
  99966. */
  99967. GlowLayer.prototype.serialize = function () {
  99968. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99969. serializationObject.customType = "BABYLON.GlowLayer";
  99970. var index;
  99971. // Included meshes
  99972. serializationObject.includedMeshes = [];
  99973. if (this._includedOnlyMeshes.length) {
  99974. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  99975. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  99976. if (mesh) {
  99977. serializationObject.includedMeshes.push(mesh.id);
  99978. }
  99979. }
  99980. }
  99981. // Excluded meshes
  99982. serializationObject.excludedMeshes = [];
  99983. if (this._excludedMeshes.length) {
  99984. for (index = 0; index < this._excludedMeshes.length; index++) {
  99985. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  99986. if (mesh) {
  99987. serializationObject.excludedMeshes.push(mesh.id);
  99988. }
  99989. }
  99990. }
  99991. return serializationObject;
  99992. };
  99993. /**
  99994. * Creates a Glow Layer from parsed glow layer data
  99995. * @param parsedGlowLayer defines glow layer data
  99996. * @param scene defines the current scene
  99997. * @param rootUrl defines the root URL containing the glow layer information
  99998. * @returns a parsed Glow Layer
  99999. */
  100000. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  100001. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  100002. var index;
  100003. // Excluded meshes
  100004. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  100005. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  100006. if (mesh) {
  100007. gl.addExcludedMesh(mesh);
  100008. }
  100009. }
  100010. // Included meshes
  100011. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  100012. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  100013. if (mesh) {
  100014. gl.addIncludedOnlyMesh(mesh);
  100015. }
  100016. }
  100017. return gl;
  100018. };
  100019. /**
  100020. * Effect Name of the layer.
  100021. */
  100022. GlowLayer.EffectName = "GlowLayer";
  100023. /**
  100024. * The default blur kernel size used for the glow.
  100025. */
  100026. GlowLayer.DefaultBlurKernelSize = 32;
  100027. /**
  100028. * The default texture size ratio used for the glow.
  100029. */
  100030. GlowLayer.DefaultTextureRatio = 0.5;
  100031. __decorate([
  100032. BABYLON.serialize()
  100033. ], GlowLayer.prototype, "blurKernelSize", null);
  100034. __decorate([
  100035. BABYLON.serialize()
  100036. ], GlowLayer.prototype, "intensity", null);
  100037. __decorate([
  100038. BABYLON.serialize("options")
  100039. ], GlowLayer.prototype, "_options", void 0);
  100040. return GlowLayer;
  100041. }(BABYLON.EffectLayer));
  100042. BABYLON.GlowLayer = GlowLayer;
  100043. })(BABYLON || (BABYLON = {}));
  100044. //# sourceMappingURL=babylon.glowLayer.js.map
  100045. var BABYLON;
  100046. (function (BABYLON) {
  100047. /**
  100048. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  100049. */
  100050. var AssetTaskState;
  100051. (function (AssetTaskState) {
  100052. /**
  100053. * Initialization
  100054. */
  100055. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  100056. /**
  100057. * Running
  100058. */
  100059. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  100060. /**
  100061. * Done
  100062. */
  100063. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  100064. /**
  100065. * Error
  100066. */
  100067. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  100068. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  100069. /**
  100070. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  100071. */
  100072. var AbstractAssetTask = /** @class */ (function () {
  100073. /**
  100074. * Creates a new {BABYLON.AssetsManager}
  100075. * @param name defines the name of the task
  100076. */
  100077. function AbstractAssetTask(
  100078. /**
  100079. * Task name
  100080. */ name) {
  100081. this.name = name;
  100082. this._isCompleted = false;
  100083. this._taskState = AssetTaskState.INIT;
  100084. }
  100085. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  100086. /**
  100087. * Get if the task is completed
  100088. */
  100089. get: function () {
  100090. return this._isCompleted;
  100091. },
  100092. enumerable: true,
  100093. configurable: true
  100094. });
  100095. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  100096. /**
  100097. * Gets the current state of the task
  100098. */
  100099. get: function () {
  100100. return this._taskState;
  100101. },
  100102. enumerable: true,
  100103. configurable: true
  100104. });
  100105. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  100106. /**
  100107. * Gets the current error object (if task is in error)
  100108. */
  100109. get: function () {
  100110. return this._errorObject;
  100111. },
  100112. enumerable: true,
  100113. configurable: true
  100114. });
  100115. /**
  100116. * Internal only
  100117. * @hidden
  100118. */
  100119. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  100120. if (this._errorObject) {
  100121. return;
  100122. }
  100123. this._errorObject = {
  100124. message: message,
  100125. exception: exception
  100126. };
  100127. };
  100128. /**
  100129. * Execute the current task
  100130. * @param scene defines the scene where you want your assets to be loaded
  100131. * @param onSuccess is a callback called when the task is successfully executed
  100132. * @param onError is a callback called if an error occurs
  100133. */
  100134. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  100135. var _this = this;
  100136. this._taskState = AssetTaskState.RUNNING;
  100137. this.runTask(scene, function () {
  100138. _this.onDoneCallback(onSuccess, onError);
  100139. }, function (msg, exception) {
  100140. _this.onErrorCallback(onError, msg, exception);
  100141. });
  100142. };
  100143. /**
  100144. * Execute the current task
  100145. * @param scene defines the scene where you want your assets to be loaded
  100146. * @param onSuccess is a callback called when the task is successfully executed
  100147. * @param onError is a callback called if an error occurs
  100148. */
  100149. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100150. throw new Error("runTask is not implemented");
  100151. };
  100152. /**
  100153. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  100154. * This can be used with failed tasks that have the reason for failure fixed.
  100155. */
  100156. AbstractAssetTask.prototype.reset = function () {
  100157. this._taskState = AssetTaskState.INIT;
  100158. };
  100159. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  100160. this._taskState = AssetTaskState.ERROR;
  100161. this._errorObject = {
  100162. message: message,
  100163. exception: exception
  100164. };
  100165. if (this.onError) {
  100166. this.onError(this, message, exception);
  100167. }
  100168. onError();
  100169. };
  100170. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  100171. try {
  100172. this._taskState = AssetTaskState.DONE;
  100173. this._isCompleted = true;
  100174. if (this.onSuccess) {
  100175. this.onSuccess(this);
  100176. }
  100177. onSuccess();
  100178. }
  100179. catch (e) {
  100180. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  100181. }
  100182. };
  100183. return AbstractAssetTask;
  100184. }());
  100185. BABYLON.AbstractAssetTask = AbstractAssetTask;
  100186. /**
  100187. * Class used to share progress information about assets loading
  100188. */
  100189. var AssetsProgressEvent = /** @class */ (function () {
  100190. /**
  100191. * Creates a {BABYLON.AssetsProgressEvent}
  100192. * @param remainingCount defines the number of remaining tasks to process
  100193. * @param totalCount defines the total number of tasks
  100194. * @param task defines the task that was just processed
  100195. */
  100196. function AssetsProgressEvent(remainingCount, totalCount, task) {
  100197. this.remainingCount = remainingCount;
  100198. this.totalCount = totalCount;
  100199. this.task = task;
  100200. }
  100201. return AssetsProgressEvent;
  100202. }());
  100203. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  100204. /**
  100205. * Define a task used by {BABYLON.AssetsManager} to load meshes
  100206. */
  100207. var MeshAssetTask = /** @class */ (function (_super) {
  100208. __extends(MeshAssetTask, _super);
  100209. /**
  100210. * Creates a new {BABYLON.MeshAssetTask}
  100211. * @param name defines the name of the task
  100212. * @param meshesNames defines the list of mesh's names you want to load
  100213. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  100214. * @param sceneFilename defines the filename of the scene to load from
  100215. */
  100216. function MeshAssetTask(
  100217. /**
  100218. * Defines the name of the task
  100219. */
  100220. name,
  100221. /**
  100222. * Defines the list of mesh's names you want to load
  100223. */
  100224. meshesNames,
  100225. /**
  100226. * Defines the root url to use as a base to load your meshes and associated resources
  100227. */
  100228. rootUrl,
  100229. /**
  100230. * Defines the filename of the scene to load from
  100231. */
  100232. sceneFilename) {
  100233. var _this = _super.call(this, name) || this;
  100234. _this.name = name;
  100235. _this.meshesNames = meshesNames;
  100236. _this.rootUrl = rootUrl;
  100237. _this.sceneFilename = sceneFilename;
  100238. return _this;
  100239. }
  100240. /**
  100241. * Execute the current task
  100242. * @param scene defines the scene where you want your assets to be loaded
  100243. * @param onSuccess is a callback called when the task is successfully executed
  100244. * @param onError is a callback called if an error occurs
  100245. */
  100246. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100247. var _this = this;
  100248. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  100249. _this.loadedMeshes = meshes;
  100250. _this.loadedParticleSystems = particleSystems;
  100251. _this.loadedSkeletons = skeletons;
  100252. onSuccess();
  100253. }, null, function (scene, message, exception) {
  100254. onError(message, exception);
  100255. });
  100256. };
  100257. return MeshAssetTask;
  100258. }(AbstractAssetTask));
  100259. BABYLON.MeshAssetTask = MeshAssetTask;
  100260. /**
  100261. * Define a task used by {BABYLON.AssetsManager} to load text content
  100262. */
  100263. var TextFileAssetTask = /** @class */ (function (_super) {
  100264. __extends(TextFileAssetTask, _super);
  100265. /**
  100266. * Creates a new TextFileAssetTask object
  100267. * @param name defines the name of the task
  100268. * @param url defines the location of the file to load
  100269. */
  100270. function TextFileAssetTask(
  100271. /**
  100272. * Defines the name of the task
  100273. */
  100274. name,
  100275. /**
  100276. * Defines the location of the file to load
  100277. */
  100278. url) {
  100279. var _this = _super.call(this, name) || this;
  100280. _this.name = name;
  100281. _this.url = url;
  100282. return _this;
  100283. }
  100284. /**
  100285. * Execute the current task
  100286. * @param scene defines the scene where you want your assets to be loaded
  100287. * @param onSuccess is a callback called when the task is successfully executed
  100288. * @param onError is a callback called if an error occurs
  100289. */
  100290. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100291. var _this = this;
  100292. scene._loadFile(this.url, function (data) {
  100293. _this.text = data;
  100294. onSuccess();
  100295. }, undefined, false, false, function (request, exception) {
  100296. if (request) {
  100297. onError(request.status + " " + request.statusText, exception);
  100298. }
  100299. });
  100300. };
  100301. return TextFileAssetTask;
  100302. }(AbstractAssetTask));
  100303. BABYLON.TextFileAssetTask = TextFileAssetTask;
  100304. /**
  100305. * Define a task used by {BABYLON.AssetsManager} to load binary data
  100306. */
  100307. var BinaryFileAssetTask = /** @class */ (function (_super) {
  100308. __extends(BinaryFileAssetTask, _super);
  100309. /**
  100310. * Creates a new BinaryFileAssetTask object
  100311. * @param name defines the name of the new task
  100312. * @param url defines the location of the file to load
  100313. */
  100314. function BinaryFileAssetTask(
  100315. /**
  100316. * Defines the name of the task
  100317. */
  100318. name,
  100319. /**
  100320. * Defines the location of the file to load
  100321. */
  100322. url) {
  100323. var _this = _super.call(this, name) || this;
  100324. _this.name = name;
  100325. _this.url = url;
  100326. return _this;
  100327. }
  100328. /**
  100329. * Execute the current task
  100330. * @param scene defines the scene where you want your assets to be loaded
  100331. * @param onSuccess is a callback called when the task is successfully executed
  100332. * @param onError is a callback called if an error occurs
  100333. */
  100334. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100335. var _this = this;
  100336. scene._loadFile(this.url, function (data) {
  100337. _this.data = data;
  100338. onSuccess();
  100339. }, undefined, true, true, function (request, exception) {
  100340. if (request) {
  100341. onError(request.status + " " + request.statusText, exception);
  100342. }
  100343. });
  100344. };
  100345. return BinaryFileAssetTask;
  100346. }(AbstractAssetTask));
  100347. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  100348. /**
  100349. * Define a task used by {BABYLON.AssetsManager} to load images
  100350. */
  100351. var ImageAssetTask = /** @class */ (function (_super) {
  100352. __extends(ImageAssetTask, _super);
  100353. /**
  100354. * Creates a new ImageAssetTask
  100355. * @param name defines the name of the task
  100356. * @param url defines the location of the image to load
  100357. */
  100358. function ImageAssetTask(
  100359. /**
  100360. * Defines the name of the task
  100361. */
  100362. name,
  100363. /**
  100364. * Defines the location of the image to load
  100365. */
  100366. url) {
  100367. var _this = _super.call(this, name) || this;
  100368. _this.name = name;
  100369. _this.url = url;
  100370. return _this;
  100371. }
  100372. /**
  100373. * Execute the current task
  100374. * @param scene defines the scene where you want your assets to be loaded
  100375. * @param onSuccess is a callback called when the task is successfully executed
  100376. * @param onError is a callback called if an error occurs
  100377. */
  100378. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100379. var _this = this;
  100380. var img = new Image();
  100381. BABYLON.Tools.SetCorsBehavior(this.url, img);
  100382. img.onload = function () {
  100383. _this.image = img;
  100384. onSuccess();
  100385. };
  100386. img.onerror = function (err) {
  100387. onError("Error loading image", err);
  100388. };
  100389. img.src = this.url;
  100390. };
  100391. return ImageAssetTask;
  100392. }(AbstractAssetTask));
  100393. BABYLON.ImageAssetTask = ImageAssetTask;
  100394. /**
  100395. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  100396. */
  100397. var TextureAssetTask = /** @class */ (function (_super) {
  100398. __extends(TextureAssetTask, _super);
  100399. /**
  100400. * Creates a new TextureAssetTask object
  100401. * @param name defines the name of the task
  100402. * @param url defines the location of the file to load
  100403. * @param noMipmap defines if mipmap should not be generated (default is false)
  100404. * @param invertY defines if texture must be inverted on Y axis (default is false)
  100405. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  100406. */
  100407. function TextureAssetTask(
  100408. /**
  100409. * Defines the name of the task
  100410. */
  100411. name,
  100412. /**
  100413. * Defines the location of the file to load
  100414. */
  100415. url,
  100416. /**
  100417. * Defines if mipmap should not be generated (default is false)
  100418. */
  100419. noMipmap,
  100420. /**
  100421. * Defines if texture must be inverted on Y axis (default is false)
  100422. */
  100423. invertY,
  100424. /**
  100425. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  100426. */
  100427. samplingMode) {
  100428. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100429. var _this = _super.call(this, name) || this;
  100430. _this.name = name;
  100431. _this.url = url;
  100432. _this.noMipmap = noMipmap;
  100433. _this.invertY = invertY;
  100434. _this.samplingMode = samplingMode;
  100435. return _this;
  100436. }
  100437. /**
  100438. * Execute the current task
  100439. * @param scene defines the scene where you want your assets to be loaded
  100440. * @param onSuccess is a callback called when the task is successfully executed
  100441. * @param onError is a callback called if an error occurs
  100442. */
  100443. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100444. var onload = function () {
  100445. onSuccess();
  100446. };
  100447. var onerror = function (message, exception) {
  100448. onError(message, exception);
  100449. };
  100450. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  100451. };
  100452. return TextureAssetTask;
  100453. }(AbstractAssetTask));
  100454. BABYLON.TextureAssetTask = TextureAssetTask;
  100455. /**
  100456. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  100457. */
  100458. var CubeTextureAssetTask = /** @class */ (function (_super) {
  100459. __extends(CubeTextureAssetTask, _super);
  100460. /**
  100461. * Creates a new CubeTextureAssetTask
  100462. * @param name defines the name of the task
  100463. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  100464. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  100465. * @param noMipmap defines if mipmaps should not be generated (default is false)
  100466. * @param files defines the explicit list of files (undefined by default)
  100467. */
  100468. function CubeTextureAssetTask(
  100469. /**
  100470. * Defines the name of the task
  100471. */
  100472. name,
  100473. /**
  100474. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  100475. */
  100476. url,
  100477. /**
  100478. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  100479. */
  100480. extensions,
  100481. /**
  100482. * Defines if mipmaps should not be generated (default is false)
  100483. */
  100484. noMipmap,
  100485. /**
  100486. * Defines the explicit list of files (undefined by default)
  100487. */
  100488. files) {
  100489. var _this = _super.call(this, name) || this;
  100490. _this.name = name;
  100491. _this.url = url;
  100492. _this.extensions = extensions;
  100493. _this.noMipmap = noMipmap;
  100494. _this.files = files;
  100495. return _this;
  100496. }
  100497. /**
  100498. * Execute the current task
  100499. * @param scene defines the scene where you want your assets to be loaded
  100500. * @param onSuccess is a callback called when the task is successfully executed
  100501. * @param onError is a callback called if an error occurs
  100502. */
  100503. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100504. var onload = function () {
  100505. onSuccess();
  100506. };
  100507. var onerror = function (message, exception) {
  100508. onError(message, exception);
  100509. };
  100510. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  100511. };
  100512. return CubeTextureAssetTask;
  100513. }(AbstractAssetTask));
  100514. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  100515. /**
  100516. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  100517. */
  100518. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  100519. __extends(HDRCubeTextureAssetTask, _super);
  100520. /**
  100521. * Creates a new HDRCubeTextureAssetTask object
  100522. * @param name defines the name of the task
  100523. * @param url defines the location of the file to load
  100524. * @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.
  100525. * @param noMipmap defines if mipmaps should not be generated (default is false)
  100526. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  100527. * @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)
  100528. * @param reserved Internal use only
  100529. */
  100530. function HDRCubeTextureAssetTask(
  100531. /**
  100532. * Defines the name of the task
  100533. */
  100534. name,
  100535. /**
  100536. * Defines the location of the file to load
  100537. */
  100538. url,
  100539. /**
  100540. * Defines the desired size (the more it increases the longer the generation will be)
  100541. */
  100542. size,
  100543. /**
  100544. * Defines if mipmaps should not be generated (default is false)
  100545. */
  100546. noMipmap,
  100547. /**
  100548. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  100549. */
  100550. generateHarmonics,
  100551. /**
  100552. * 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)
  100553. */
  100554. gammaSpace,
  100555. /**
  100556. * Internal Use Only
  100557. */
  100558. reserved) {
  100559. if (noMipmap === void 0) { noMipmap = false; }
  100560. if (generateHarmonics === void 0) { generateHarmonics = true; }
  100561. if (gammaSpace === void 0) { gammaSpace = false; }
  100562. if (reserved === void 0) { reserved = false; }
  100563. var _this = _super.call(this, name) || this;
  100564. _this.name = name;
  100565. _this.url = url;
  100566. _this.size = size;
  100567. _this.noMipmap = noMipmap;
  100568. _this.generateHarmonics = generateHarmonics;
  100569. _this.gammaSpace = gammaSpace;
  100570. _this.reserved = reserved;
  100571. return _this;
  100572. }
  100573. /**
  100574. * Execute the current task
  100575. * @param scene defines the scene where you want your assets to be loaded
  100576. * @param onSuccess is a callback called when the task is successfully executed
  100577. * @param onError is a callback called if an error occurs
  100578. */
  100579. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  100580. var onload = function () {
  100581. onSuccess();
  100582. };
  100583. var onerror = function (message, exception) {
  100584. onError(message, exception);
  100585. };
  100586. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  100587. };
  100588. return HDRCubeTextureAssetTask;
  100589. }(AbstractAssetTask));
  100590. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  100591. /**
  100592. * This class can be used to easily import assets into a scene
  100593. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  100594. */
  100595. var AssetsManager = /** @class */ (function () {
  100596. /**
  100597. * Creates a new AssetsManager
  100598. * @param scene defines the scene to work on
  100599. */
  100600. function AssetsManager(scene) {
  100601. this._isLoading = false;
  100602. this._tasks = new Array();
  100603. this._waitingTasksCount = 0;
  100604. this._totalTasksCount = 0;
  100605. /**
  100606. * Observable called when all tasks are processed
  100607. */
  100608. this.onTaskSuccessObservable = new BABYLON.Observable();
  100609. /**
  100610. * Observable called when a task had an error
  100611. */
  100612. this.onTaskErrorObservable = new BABYLON.Observable();
  100613. /**
  100614. * Observable called when a task is successful
  100615. */
  100616. this.onTasksDoneObservable = new BABYLON.Observable();
  100617. /**
  100618. * Observable called when a task is done (whatever the result is)
  100619. */
  100620. this.onProgressObservable = new BABYLON.Observable();
  100621. /**
  100622. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  100623. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  100624. */
  100625. this.useDefaultLoadingScreen = true;
  100626. this._scene = scene;
  100627. }
  100628. /**
  100629. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  100630. * @param taskName defines the name of the new task
  100631. * @param meshesNames defines the name of meshes to load
  100632. * @param rootUrl defines the root url to use to locate files
  100633. * @param sceneFilename defines the filename of the scene file
  100634. * @returns a new {BABYLON.MeshAssetTask} object
  100635. */
  100636. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  100637. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  100638. this._tasks.push(task);
  100639. return task;
  100640. };
  100641. /**
  100642. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  100643. * @param taskName defines the name of the new task
  100644. * @param url defines the url of the file to load
  100645. * @returns a new {BABYLON.TextFileAssetTask} object
  100646. */
  100647. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  100648. var task = new TextFileAssetTask(taskName, url);
  100649. this._tasks.push(task);
  100650. return task;
  100651. };
  100652. /**
  100653. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  100654. * @param taskName defines the name of the new task
  100655. * @param url defines the url of the file to load
  100656. * @returns a new {BABYLON.BinaryFileAssetTask} object
  100657. */
  100658. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  100659. var task = new BinaryFileAssetTask(taskName, url);
  100660. this._tasks.push(task);
  100661. return task;
  100662. };
  100663. /**
  100664. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  100665. * @param taskName defines the name of the new task
  100666. * @param url defines the url of the file to load
  100667. * @returns a new {BABYLON.ImageAssetTask} object
  100668. */
  100669. AssetsManager.prototype.addImageTask = function (taskName, url) {
  100670. var task = new ImageAssetTask(taskName, url);
  100671. this._tasks.push(task);
  100672. return task;
  100673. };
  100674. /**
  100675. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  100676. * @param taskName defines the name of the new task
  100677. * @param url defines the url of the file to load
  100678. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  100679. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  100680. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  100681. * @returns a new {BABYLON.TextureAssetTask} object
  100682. */
  100683. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  100684. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100685. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  100686. this._tasks.push(task);
  100687. return task;
  100688. };
  100689. /**
  100690. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  100691. * @param taskName defines the name of the new task
  100692. * @param url defines the url of the file to load
  100693. * @param extensions defines the extension to use to load the cube map (can be null)
  100694. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  100695. * @param files defines the list of files to load (can be null)
  100696. * @returns a new {BABYLON.CubeTextureAssetTask} object
  100697. */
  100698. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  100699. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  100700. this._tasks.push(task);
  100701. return task;
  100702. };
  100703. /**
  100704. *
  100705. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  100706. * @param taskName defines the name of the new task
  100707. * @param url defines the url of the file to load
  100708. * @param size defines the size you want for the cubemap (can be null)
  100709. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  100710. * @param generateHarmonics defines if you want to automatically generate (true by default)
  100711. * @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)
  100712. * @param reserved Internal use only
  100713. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  100714. */
  100715. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  100716. if (noMipmap === void 0) { noMipmap = false; }
  100717. if (generateHarmonics === void 0) { generateHarmonics = true; }
  100718. if (gammaSpace === void 0) { gammaSpace = false; }
  100719. if (reserved === void 0) { reserved = false; }
  100720. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  100721. this._tasks.push(task);
  100722. return task;
  100723. };
  100724. /**
  100725. * Remove a task from the assets manager.
  100726. * @param task the task to remove
  100727. */
  100728. AssetsManager.prototype.removeTask = function (task) {
  100729. var index = this._tasks.indexOf(task);
  100730. if (index > -1) {
  100731. this._tasks.splice(index, 1);
  100732. }
  100733. };
  100734. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  100735. this._waitingTasksCount--;
  100736. try {
  100737. if (this.onProgress) {
  100738. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  100739. }
  100740. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  100741. }
  100742. catch (e) {
  100743. BABYLON.Tools.Error("Error running progress callbacks.");
  100744. console.log(e);
  100745. }
  100746. if (this._waitingTasksCount === 0) {
  100747. try {
  100748. if (this.onFinish) {
  100749. this.onFinish(this._tasks);
  100750. }
  100751. // Let's remove successfull tasks
  100752. var currentTasks = this._tasks.slice();
  100753. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  100754. var task = currentTasks_1[_i];
  100755. if (task.taskState === AssetTaskState.DONE) {
  100756. var index = this._tasks.indexOf(task);
  100757. if (index > -1) {
  100758. this._tasks.splice(index, 1);
  100759. }
  100760. }
  100761. }
  100762. this.onTasksDoneObservable.notifyObservers(this._tasks);
  100763. }
  100764. catch (e) {
  100765. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  100766. console.log(e);
  100767. }
  100768. this._isLoading = false;
  100769. this._scene.getEngine().hideLoadingUI();
  100770. }
  100771. };
  100772. AssetsManager.prototype._runTask = function (task) {
  100773. var _this = this;
  100774. var done = function () {
  100775. try {
  100776. if (_this.onTaskSuccess) {
  100777. _this.onTaskSuccess(task);
  100778. }
  100779. _this.onTaskSuccessObservable.notifyObservers(task);
  100780. _this._decreaseWaitingTasksCount(task);
  100781. }
  100782. catch (e) {
  100783. error("Error executing task success callbacks", e);
  100784. }
  100785. };
  100786. var error = function (message, exception) {
  100787. task._setErrorObject(message, exception);
  100788. if (_this.onTaskError) {
  100789. _this.onTaskError(task);
  100790. }
  100791. _this.onTaskErrorObservable.notifyObservers(task);
  100792. _this._decreaseWaitingTasksCount(task);
  100793. };
  100794. task.run(this._scene, done, error);
  100795. };
  100796. /**
  100797. * Reset the {BABYLON.AssetsManager} and remove all tasks
  100798. * @return the current instance of the {BABYLON.AssetsManager}
  100799. */
  100800. AssetsManager.prototype.reset = function () {
  100801. this._isLoading = false;
  100802. this._tasks = new Array();
  100803. return this;
  100804. };
  100805. /**
  100806. * Start the loading process
  100807. * @return the current instance of the {BABYLON.AssetsManager}
  100808. */
  100809. AssetsManager.prototype.load = function () {
  100810. if (this._isLoading) {
  100811. return this;
  100812. }
  100813. this._isLoading = true;
  100814. this._waitingTasksCount = this._tasks.length;
  100815. this._totalTasksCount = this._tasks.length;
  100816. if (this._waitingTasksCount === 0) {
  100817. this._isLoading = false;
  100818. if (this.onFinish) {
  100819. this.onFinish(this._tasks);
  100820. }
  100821. this.onTasksDoneObservable.notifyObservers(this._tasks);
  100822. return this;
  100823. }
  100824. if (this.useDefaultLoadingScreen) {
  100825. this._scene.getEngine().displayLoadingUI();
  100826. }
  100827. for (var index = 0; index < this._tasks.length; index++) {
  100828. var task = this._tasks[index];
  100829. if (task.taskState === AssetTaskState.INIT) {
  100830. this._runTask(task);
  100831. }
  100832. }
  100833. return this;
  100834. };
  100835. return AssetsManager;
  100836. }());
  100837. BABYLON.AssetsManager = AssetsManager;
  100838. })(BABYLON || (BABYLON = {}));
  100839. //# sourceMappingURL=babylon.assetsManager.js.map
  100840. var BABYLON;
  100841. (function (BABYLON) {
  100842. var serializedGeometries = [];
  100843. var serializeGeometry = function (geometry, serializationGeometries) {
  100844. if (serializedGeometries[geometry.id]) {
  100845. return;
  100846. }
  100847. if (geometry.doNotSerialize) {
  100848. return;
  100849. }
  100850. if (geometry instanceof BABYLON.BoxGeometry) {
  100851. serializationGeometries.boxes.push(geometry.serialize());
  100852. }
  100853. else if (geometry instanceof BABYLON.SphereGeometry) {
  100854. serializationGeometries.spheres.push(geometry.serialize());
  100855. }
  100856. else if (geometry instanceof BABYLON.CylinderGeometry) {
  100857. serializationGeometries.cylinders.push(geometry.serialize());
  100858. }
  100859. else if (geometry instanceof BABYLON.TorusGeometry) {
  100860. serializationGeometries.toruses.push(geometry.serialize());
  100861. }
  100862. else if (geometry instanceof BABYLON.GroundGeometry) {
  100863. serializationGeometries.grounds.push(geometry.serialize());
  100864. }
  100865. else if (geometry instanceof BABYLON.Plane) {
  100866. serializationGeometries.planes.push(geometry.serialize());
  100867. }
  100868. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  100869. serializationGeometries.torusKnots.push(geometry.serialize());
  100870. }
  100871. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  100872. throw new Error("Unknown primitive type");
  100873. }
  100874. else {
  100875. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  100876. }
  100877. serializedGeometries[geometry.id] = true;
  100878. };
  100879. var serializeMesh = function (mesh, serializationScene) {
  100880. var serializationObject = {};
  100881. // Geometry
  100882. var geometry = mesh._geometry;
  100883. if (geometry) {
  100884. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  100885. // 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
  100886. serializeGeometry(geometry, serializationScene.geometries);
  100887. }
  100888. }
  100889. // Custom
  100890. if (mesh.serialize) {
  100891. mesh.serialize(serializationObject);
  100892. }
  100893. return serializationObject;
  100894. };
  100895. var finalizeSingleMesh = function (mesh, serializationObject) {
  100896. //only works if the mesh is already loaded
  100897. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  100898. //serialize material
  100899. if (mesh.material) {
  100900. if (mesh.material instanceof BABYLON.MultiMaterial) {
  100901. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  100902. serializationObject.materials = serializationObject.materials || [];
  100903. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  100904. serializationObject.multiMaterials.push(mesh.material.serialize());
  100905. var _loop_1 = function (submaterial) {
  100906. if (submaterial) {
  100907. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  100908. serializationObject.materials.push(submaterial.serialize());
  100909. }
  100910. }
  100911. };
  100912. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  100913. var submaterial = _a[_i];
  100914. _loop_1(submaterial);
  100915. }
  100916. }
  100917. }
  100918. else {
  100919. serializationObject.materials = serializationObject.materials || [];
  100920. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  100921. serializationObject.materials.push(mesh.material.serialize());
  100922. }
  100923. }
  100924. }
  100925. //serialize geometry
  100926. var geometry = mesh._geometry;
  100927. if (geometry) {
  100928. if (!serializationObject.geometries) {
  100929. serializationObject.geometries = {};
  100930. serializationObject.geometries.boxes = [];
  100931. serializationObject.geometries.spheres = [];
  100932. serializationObject.geometries.cylinders = [];
  100933. serializationObject.geometries.toruses = [];
  100934. serializationObject.geometries.grounds = [];
  100935. serializationObject.geometries.planes = [];
  100936. serializationObject.geometries.torusKnots = [];
  100937. serializationObject.geometries.vertexData = [];
  100938. }
  100939. serializeGeometry(geometry, serializationObject.geometries);
  100940. }
  100941. // Skeletons
  100942. if (mesh.skeleton) {
  100943. serializationObject.skeletons = serializationObject.skeletons || [];
  100944. serializationObject.skeletons.push(mesh.skeleton.serialize());
  100945. }
  100946. //serialize the actual mesh
  100947. serializationObject.meshes = serializationObject.meshes || [];
  100948. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  100949. }
  100950. };
  100951. var SceneSerializer = /** @class */ (function () {
  100952. function SceneSerializer() {
  100953. }
  100954. SceneSerializer.ClearCache = function () {
  100955. serializedGeometries = [];
  100956. };
  100957. SceneSerializer.Serialize = function (scene) {
  100958. var serializationObject = {};
  100959. SceneSerializer.ClearCache();
  100960. // Scene
  100961. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  100962. serializationObject.autoClear = scene.autoClear;
  100963. serializationObject.clearColor = scene.clearColor.asArray();
  100964. serializationObject.ambientColor = scene.ambientColor.asArray();
  100965. serializationObject.gravity = scene.gravity.asArray();
  100966. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  100967. serializationObject.workerCollisions = scene.workerCollisions;
  100968. // Fog
  100969. if (scene.fogMode && scene.fogMode !== 0) {
  100970. serializationObject.fogMode = scene.fogMode;
  100971. serializationObject.fogColor = scene.fogColor.asArray();
  100972. serializationObject.fogStart = scene.fogStart;
  100973. serializationObject.fogEnd = scene.fogEnd;
  100974. serializationObject.fogDensity = scene.fogDensity;
  100975. }
  100976. //Physics
  100977. if (scene.isPhysicsEnabled()) {
  100978. var physicEngine = scene.getPhysicsEngine();
  100979. if (physicEngine) {
  100980. serializationObject.physicsEnabled = true;
  100981. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  100982. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  100983. }
  100984. }
  100985. // Metadata
  100986. if (scene.metadata) {
  100987. serializationObject.metadata = scene.metadata;
  100988. }
  100989. // Morph targets
  100990. serializationObject.morphTargetManagers = [];
  100991. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  100992. var abstractMesh = _a[_i];
  100993. var manager = abstractMesh.morphTargetManager;
  100994. if (manager) {
  100995. serializationObject.morphTargetManagers.push(manager.serialize());
  100996. }
  100997. }
  100998. // Lights
  100999. serializationObject.lights = [];
  101000. var index;
  101001. var light;
  101002. for (index = 0; index < scene.lights.length; index++) {
  101003. light = scene.lights[index];
  101004. if (!light.doNotSerialize) {
  101005. serializationObject.lights.push(light.serialize());
  101006. }
  101007. }
  101008. // Cameras
  101009. serializationObject.cameras = [];
  101010. for (index = 0; index < scene.cameras.length; index++) {
  101011. var camera = scene.cameras[index];
  101012. if (!camera.doNotSerialize) {
  101013. serializationObject.cameras.push(camera.serialize());
  101014. }
  101015. }
  101016. if (scene.activeCamera) {
  101017. serializationObject.activeCameraID = scene.activeCamera.id;
  101018. }
  101019. // Animations
  101020. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  101021. // Materials
  101022. serializationObject.materials = [];
  101023. serializationObject.multiMaterials = [];
  101024. var material;
  101025. for (index = 0; index < scene.materials.length; index++) {
  101026. material = scene.materials[index];
  101027. if (!material.doNotSerialize) {
  101028. serializationObject.materials.push(material.serialize());
  101029. }
  101030. }
  101031. // MultiMaterials
  101032. serializationObject.multiMaterials = [];
  101033. for (index = 0; index < scene.multiMaterials.length; index++) {
  101034. var multiMaterial = scene.multiMaterials[index];
  101035. serializationObject.multiMaterials.push(multiMaterial.serialize());
  101036. }
  101037. // Environment texture
  101038. if (scene.environmentTexture) {
  101039. serializationObject.environmentTexture = scene.environmentTexture.name;
  101040. }
  101041. // Skeletons
  101042. serializationObject.skeletons = [];
  101043. for (index = 0; index < scene.skeletons.length; index++) {
  101044. var skeleton = scene.skeletons[index];
  101045. if (!skeleton.doNotSerialize) {
  101046. serializationObject.skeletons.push(skeleton.serialize());
  101047. }
  101048. }
  101049. // Transform nodes
  101050. serializationObject.transformNodes = [];
  101051. for (index = 0; index < scene.transformNodes.length; index++) {
  101052. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  101053. }
  101054. // Geometries
  101055. serializationObject.geometries = {};
  101056. serializationObject.geometries.boxes = [];
  101057. serializationObject.geometries.spheres = [];
  101058. serializationObject.geometries.cylinders = [];
  101059. serializationObject.geometries.toruses = [];
  101060. serializationObject.geometries.grounds = [];
  101061. serializationObject.geometries.planes = [];
  101062. serializationObject.geometries.torusKnots = [];
  101063. serializationObject.geometries.vertexData = [];
  101064. serializedGeometries = [];
  101065. var geometries = scene.getGeometries();
  101066. for (index = 0; index < geometries.length; index++) {
  101067. var geometry = geometries[index];
  101068. if (geometry.isReady()) {
  101069. serializeGeometry(geometry, serializationObject.geometries);
  101070. }
  101071. }
  101072. // Meshes
  101073. serializationObject.meshes = [];
  101074. for (index = 0; index < scene.meshes.length; index++) {
  101075. var abstractMesh = scene.meshes[index];
  101076. if (abstractMesh instanceof BABYLON.Mesh) {
  101077. var mesh = abstractMesh;
  101078. if (!mesh.doNotSerialize) {
  101079. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  101080. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  101081. }
  101082. }
  101083. }
  101084. }
  101085. // Particles Systems
  101086. serializationObject.particleSystems = [];
  101087. for (index = 0; index < scene.particleSystems.length; index++) {
  101088. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  101089. }
  101090. // Shadows
  101091. serializationObject.shadowGenerators = [];
  101092. for (index = 0; index < scene.lights.length; index++) {
  101093. light = scene.lights[index];
  101094. var shadowGenerator = light.getShadowGenerator();
  101095. if (shadowGenerator) {
  101096. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  101097. }
  101098. }
  101099. // Action Manager
  101100. if (scene.actionManager) {
  101101. serializationObject.actions = scene.actionManager.serialize("scene");
  101102. }
  101103. // Audio
  101104. serializationObject.sounds = [];
  101105. for (index = 0; index < scene.soundTracks.length; index++) {
  101106. var soundtrack = scene.soundTracks[index];
  101107. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  101108. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  101109. }
  101110. }
  101111. // Components
  101112. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  101113. var component = _c[_b];
  101114. component.serialize(serializationObject);
  101115. }
  101116. return serializationObject;
  101117. };
  101118. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  101119. if (withParents === void 0) { withParents = false; }
  101120. if (withChildren === void 0) { withChildren = false; }
  101121. var serializationObject = {};
  101122. SceneSerializer.ClearCache();
  101123. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  101124. if (withParents || withChildren) {
  101125. //deliberate for loop! not for each, appended should be processed as well.
  101126. for (var i = 0; i < toSerialize.length; ++i) {
  101127. if (withChildren) {
  101128. toSerialize[i].getDescendants().forEach(function (node) {
  101129. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  101130. toSerialize.push(node);
  101131. }
  101132. });
  101133. }
  101134. //make sure the array doesn't contain the object already
  101135. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  101136. toSerialize.push(toSerialize[i].parent);
  101137. }
  101138. }
  101139. }
  101140. toSerialize.forEach(function (mesh) {
  101141. finalizeSingleMesh(mesh, serializationObject);
  101142. });
  101143. return serializationObject;
  101144. };
  101145. return SceneSerializer;
  101146. }());
  101147. BABYLON.SceneSerializer = SceneSerializer;
  101148. })(BABYLON || (BABYLON = {}));
  101149. //# sourceMappingURL=babylon.sceneSerializer.js.map
  101150. var BABYLON;
  101151. (function (BABYLON) {
  101152. /**
  101153. * Class used to generate realtime reflection / refraction cube textures
  101154. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  101155. */
  101156. var ReflectionProbe = /** @class */ (function () {
  101157. /**
  101158. * Creates a new reflection probe
  101159. * @param name defines the name of the probe
  101160. * @param size defines the texture resolution (for each face)
  101161. * @param scene defines the hosting scene
  101162. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  101163. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  101164. */
  101165. function ReflectionProbe(
  101166. /** defines the name of the probe */
  101167. name, size, scene, generateMipMaps, useFloat) {
  101168. if (generateMipMaps === void 0) { generateMipMaps = true; }
  101169. if (useFloat === void 0) { useFloat = false; }
  101170. var _this = this;
  101171. this.name = name;
  101172. this._viewMatrix = BABYLON.Matrix.Identity();
  101173. this._target = BABYLON.Vector3.Zero();
  101174. this._add = BABYLON.Vector3.Zero();
  101175. this._invertYAxis = false;
  101176. /** Gets or sets probe position (center of the cube map) */
  101177. this.position = BABYLON.Vector3.Zero();
  101178. this._scene = scene;
  101179. this._scene.reflectionProbes.push(this);
  101180. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  101181. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  101182. switch (faceIndex) {
  101183. case 0:
  101184. _this._add.copyFromFloats(1, 0, 0);
  101185. break;
  101186. case 1:
  101187. _this._add.copyFromFloats(-1, 0, 0);
  101188. break;
  101189. case 2:
  101190. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  101191. break;
  101192. case 3:
  101193. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  101194. break;
  101195. case 4:
  101196. _this._add.copyFromFloats(0, 0, 1);
  101197. break;
  101198. case 5:
  101199. _this._add.copyFromFloats(0, 0, -1);
  101200. break;
  101201. }
  101202. if (_this._attachedMesh) {
  101203. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  101204. }
  101205. _this.position.addToRef(_this._add, _this._target);
  101206. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  101207. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  101208. scene._forcedViewPosition = _this.position;
  101209. });
  101210. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  101211. scene._forcedViewPosition = null;
  101212. scene.updateTransformMatrix(true);
  101213. });
  101214. if (scene.activeCamera) {
  101215. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  101216. }
  101217. }
  101218. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  101219. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  101220. get: function () {
  101221. return this._renderTargetTexture.samples;
  101222. },
  101223. set: function (value) {
  101224. this._renderTargetTexture.samples = value;
  101225. },
  101226. enumerable: true,
  101227. configurable: true
  101228. });
  101229. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  101230. /** Gets or sets the refresh rate to use (on every frame by default) */
  101231. get: function () {
  101232. return this._renderTargetTexture.refreshRate;
  101233. },
  101234. set: function (value) {
  101235. this._renderTargetTexture.refreshRate = value;
  101236. },
  101237. enumerable: true,
  101238. configurable: true
  101239. });
  101240. /**
  101241. * Gets the hosting scene
  101242. * @returns a Scene
  101243. */
  101244. ReflectionProbe.prototype.getScene = function () {
  101245. return this._scene;
  101246. };
  101247. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  101248. /** Gets the internal CubeTexture used to render to */
  101249. get: function () {
  101250. return this._renderTargetTexture;
  101251. },
  101252. enumerable: true,
  101253. configurable: true
  101254. });
  101255. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  101256. /** Gets the list of meshes to render */
  101257. get: function () {
  101258. return this._renderTargetTexture.renderList;
  101259. },
  101260. enumerable: true,
  101261. configurable: true
  101262. });
  101263. /**
  101264. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  101265. * @param mesh defines the mesh to attach to
  101266. */
  101267. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  101268. this._attachedMesh = mesh;
  101269. };
  101270. /**
  101271. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  101272. * @param renderingGroupId The rendering group id corresponding to its index
  101273. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  101274. */
  101275. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  101276. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  101277. };
  101278. /**
  101279. * Clean all associated resources
  101280. */
  101281. ReflectionProbe.prototype.dispose = function () {
  101282. var index = this._scene.reflectionProbes.indexOf(this);
  101283. if (index !== -1) {
  101284. // Remove from the scene if found
  101285. this._scene.reflectionProbes.splice(index, 1);
  101286. }
  101287. if (this._renderTargetTexture) {
  101288. this._renderTargetTexture.dispose();
  101289. this._renderTargetTexture = null;
  101290. }
  101291. };
  101292. return ReflectionProbe;
  101293. }());
  101294. BABYLON.ReflectionProbe = ReflectionProbe;
  101295. })(BABYLON || (BABYLON = {}));
  101296. //# sourceMappingURL=babylon.reflectionProbe.js.map
  101297. var BABYLON;
  101298. (function (BABYLON) {
  101299. /**
  101300. * Defines the layer scene component responsible to manage any layers
  101301. * in a given scene.
  101302. */
  101303. var LayerSceneComponent = /** @class */ (function () {
  101304. /**
  101305. * Creates a new instance of the component for the given scene
  101306. * @param scene Defines the scene to register the component in
  101307. */
  101308. function LayerSceneComponent(scene) {
  101309. /**
  101310. * The component name helpfull to identify the component in the list of scene components.
  101311. */
  101312. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  101313. this.scene = scene;
  101314. this._engine = scene.getEngine();
  101315. scene.layers = new Array();
  101316. }
  101317. /**
  101318. * Registers the component in a given scene
  101319. */
  101320. LayerSceneComponent.prototype.register = function () {
  101321. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  101322. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  101323. };
  101324. /**
  101325. * Rebuilds the elements related to this component in case of
  101326. * context lost for instance.
  101327. */
  101328. LayerSceneComponent.prototype.rebuild = function () {
  101329. var layers = this.scene.layers;
  101330. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  101331. var layer = layers_1[_i];
  101332. layer._rebuild();
  101333. }
  101334. };
  101335. /**
  101336. * Disposes the component and the associated ressources.
  101337. */
  101338. LayerSceneComponent.prototype.dispose = function () {
  101339. var layers = this.scene.layers;
  101340. while (layers.length) {
  101341. layers[0].dispose();
  101342. }
  101343. };
  101344. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  101345. var layers = this.scene.layers;
  101346. if (layers.length) {
  101347. this._engine.setDepthBuffer(false);
  101348. var cameraLayerMask = camera.layerMask;
  101349. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  101350. var layer = layers_2[_i];
  101351. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  101352. layer.render();
  101353. }
  101354. }
  101355. this._engine.setDepthBuffer(true);
  101356. }
  101357. };
  101358. LayerSceneComponent.prototype._drawBackground = function (camera) {
  101359. this._draw(camera, true);
  101360. };
  101361. LayerSceneComponent.prototype._drawForeground = function (camera) {
  101362. this._draw(camera, false);
  101363. };
  101364. return LayerSceneComponent;
  101365. }());
  101366. BABYLON.LayerSceneComponent = LayerSceneComponent;
  101367. })(BABYLON || (BABYLON = {}));
  101368. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  101369. var BABYLON;
  101370. (function (BABYLON) {
  101371. var Layer = /** @class */ (function () {
  101372. function Layer(name, imgUrl, scene, isBackground, color) {
  101373. this.name = name;
  101374. this.scale = new BABYLON.Vector2(1, 1);
  101375. this.offset = new BABYLON.Vector2(0, 0);
  101376. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  101377. this.layerMask = 0x0FFFFFFF;
  101378. this._vertexBuffers = {};
  101379. // Events
  101380. /**
  101381. * An event triggered when the layer is disposed.
  101382. */
  101383. this.onDisposeObservable = new BABYLON.Observable();
  101384. /**
  101385. * An event triggered before rendering the scene
  101386. */
  101387. this.onBeforeRenderObservable = new BABYLON.Observable();
  101388. /**
  101389. * An event triggered after rendering the scene
  101390. */
  101391. this.onAfterRenderObservable = new BABYLON.Observable();
  101392. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  101393. this.isBackground = isBackground === undefined ? true : isBackground;
  101394. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  101395. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  101396. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  101397. if (!layerComponent) {
  101398. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  101399. this._scene._addComponent(layerComponent);
  101400. }
  101401. this._scene.layers.push(this);
  101402. var engine = this._scene.getEngine();
  101403. // VBO
  101404. var vertices = [];
  101405. vertices.push(1, 1);
  101406. vertices.push(-1, 1);
  101407. vertices.push(-1, -1);
  101408. vertices.push(1, -1);
  101409. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  101410. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  101411. this._createIndexBuffer();
  101412. // Effects
  101413. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  101414. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  101415. }
  101416. Object.defineProperty(Layer.prototype, "onDispose", {
  101417. set: function (callback) {
  101418. if (this._onDisposeObserver) {
  101419. this.onDisposeObservable.remove(this._onDisposeObserver);
  101420. }
  101421. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  101422. },
  101423. enumerable: true,
  101424. configurable: true
  101425. });
  101426. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  101427. set: function (callback) {
  101428. if (this._onBeforeRenderObserver) {
  101429. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  101430. }
  101431. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  101432. },
  101433. enumerable: true,
  101434. configurable: true
  101435. });
  101436. Object.defineProperty(Layer.prototype, "onAfterRender", {
  101437. set: function (callback) {
  101438. if (this._onAfterRenderObserver) {
  101439. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101440. }
  101441. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  101442. },
  101443. enumerable: true,
  101444. configurable: true
  101445. });
  101446. Layer.prototype._createIndexBuffer = function () {
  101447. var engine = this._scene.getEngine();
  101448. // Indices
  101449. var indices = [];
  101450. indices.push(0);
  101451. indices.push(1);
  101452. indices.push(2);
  101453. indices.push(0);
  101454. indices.push(2);
  101455. indices.push(3);
  101456. this._indexBuffer = engine.createIndexBuffer(indices);
  101457. };
  101458. /** @hidden */
  101459. Layer.prototype._rebuild = function () {
  101460. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  101461. if (vb) {
  101462. vb._rebuild();
  101463. }
  101464. this._createIndexBuffer();
  101465. };
  101466. Layer.prototype.render = function () {
  101467. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  101468. // Check
  101469. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  101470. return;
  101471. var engine = this._scene.getEngine();
  101472. this.onBeforeRenderObservable.notifyObservers(this);
  101473. // Render
  101474. engine.enableEffect(currentEffect);
  101475. engine.setState(false);
  101476. // Texture
  101477. currentEffect.setTexture("textureSampler", this.texture);
  101478. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  101479. // Color
  101480. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  101481. // Scale / offset
  101482. currentEffect.setVector2("offset", this.offset);
  101483. currentEffect.setVector2("scale", this.scale);
  101484. // VBOs
  101485. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  101486. // Draw order
  101487. if (!this.alphaTest) {
  101488. engine.setAlphaMode(this.alphaBlendingMode);
  101489. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101490. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  101491. }
  101492. else {
  101493. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101494. }
  101495. this.onAfterRenderObservable.notifyObservers(this);
  101496. };
  101497. Layer.prototype.dispose = function () {
  101498. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  101499. if (vertexBuffer) {
  101500. vertexBuffer.dispose();
  101501. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  101502. }
  101503. if (this._indexBuffer) {
  101504. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  101505. this._indexBuffer = null;
  101506. }
  101507. if (this.texture) {
  101508. this.texture.dispose();
  101509. this.texture = null;
  101510. }
  101511. // Remove from scene
  101512. var index = this._scene.layers.indexOf(this);
  101513. this._scene.layers.splice(index, 1);
  101514. // Callback
  101515. this.onDisposeObservable.notifyObservers(this);
  101516. this.onDisposeObservable.clear();
  101517. this.onAfterRenderObservable.clear();
  101518. this.onBeforeRenderObservable.clear();
  101519. };
  101520. return Layer;
  101521. }());
  101522. BABYLON.Layer = Layer;
  101523. })(BABYLON || (BABYLON = {}));
  101524. //# sourceMappingURL=babylon.layer.js.map
  101525. var BABYLON;
  101526. (function (BABYLON) {
  101527. var TextureTools = /** @class */ (function () {
  101528. function TextureTools() {
  101529. }
  101530. /**
  101531. * Uses the GPU to create a copy texture rescaled at a given size
  101532. * @param texture Texture to copy from
  101533. * @param width Desired width
  101534. * @param height Desired height
  101535. * @return Generated texture
  101536. */
  101537. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  101538. if (useBilinearMode === void 0) { useBilinearMode = true; }
  101539. var scene = texture.getScene();
  101540. var engine = scene.getEngine();
  101541. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  101542. rtt.wrapU = texture.wrapU;
  101543. rtt.wrapV = texture.wrapV;
  101544. rtt.uOffset = texture.uOffset;
  101545. rtt.vOffset = texture.vOffset;
  101546. rtt.uScale = texture.uScale;
  101547. rtt.vScale = texture.vScale;
  101548. rtt.uAng = texture.uAng;
  101549. rtt.vAng = texture.vAng;
  101550. rtt.wAng = texture.wAng;
  101551. rtt.coordinatesIndex = texture.coordinatesIndex;
  101552. rtt.level = texture.level;
  101553. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  101554. rtt._texture.isReady = false;
  101555. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101556. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101557. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  101558. passPostProcess.getEffect().executeWhenCompiled(function () {
  101559. passPostProcess.onApply = function (effect) {
  101560. effect.setTexture("textureSampler", texture);
  101561. };
  101562. var internalTexture = rtt.getInternalTexture();
  101563. if (internalTexture) {
  101564. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  101565. engine.unBindFramebuffer(internalTexture);
  101566. rtt.disposeFramebufferObjects();
  101567. passPostProcess.dispose();
  101568. internalTexture.isReady = true;
  101569. }
  101570. });
  101571. return rtt;
  101572. };
  101573. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  101574. if (!scene._environmentBRDFTexture) {
  101575. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101576. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101577. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101578. scene._environmentBRDFTexture = texture;
  101579. }
  101580. return scene._environmentBRDFTexture;
  101581. };
  101582. 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=";
  101583. return TextureTools;
  101584. }());
  101585. BABYLON.TextureTools = TextureTools;
  101586. })(BABYLON || (BABYLON = {}));
  101587. //# sourceMappingURL=babylon.textureTools.js.map
  101588. var BABYLON;
  101589. (function (BABYLON) {
  101590. var FramingBehavior = /** @class */ (function () {
  101591. function FramingBehavior() {
  101592. this._mode = FramingBehavior.FitFrustumSidesMode;
  101593. this._radiusScale = 1.0;
  101594. this._positionScale = 0.5;
  101595. this._defaultElevation = 0.3;
  101596. this._elevationReturnTime = 1500;
  101597. this._elevationReturnWaitTime = 1000;
  101598. this._zoomStopsAnimation = false;
  101599. this._framingTime = 1500;
  101600. this._isPointerDown = false;
  101601. this._lastInteractionTime = -Infinity;
  101602. // Framing control
  101603. this._animatables = new Array();
  101604. this._betaIsAnimating = false;
  101605. }
  101606. Object.defineProperty(FramingBehavior.prototype, "name", {
  101607. get: function () {
  101608. return "Framing";
  101609. },
  101610. enumerable: true,
  101611. configurable: true
  101612. });
  101613. Object.defineProperty(FramingBehavior.prototype, "mode", {
  101614. /**
  101615. * Gets current mode used by the behavior.
  101616. */
  101617. get: function () {
  101618. return this._mode;
  101619. },
  101620. /**
  101621. * Sets the current mode used by the behavior
  101622. */
  101623. set: function (mode) {
  101624. this._mode = mode;
  101625. },
  101626. enumerable: true,
  101627. configurable: true
  101628. });
  101629. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  101630. /**
  101631. * Gets the scale applied to the radius
  101632. */
  101633. get: function () {
  101634. return this._radiusScale;
  101635. },
  101636. /**
  101637. * Sets the scale applied to the radius (1 by default)
  101638. */
  101639. set: function (radius) {
  101640. this._radiusScale = radius;
  101641. },
  101642. enumerable: true,
  101643. configurable: true
  101644. });
  101645. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  101646. /**
  101647. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  101648. */
  101649. get: function () {
  101650. return this._positionScale;
  101651. },
  101652. /**
  101653. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  101654. */
  101655. set: function (scale) {
  101656. this._positionScale = scale;
  101657. },
  101658. enumerable: true,
  101659. configurable: true
  101660. });
  101661. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  101662. /**
  101663. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  101664. * behaviour is triggered, in radians.
  101665. */
  101666. get: function () {
  101667. return this._defaultElevation;
  101668. },
  101669. /**
  101670. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  101671. * behaviour is triggered, in radians.
  101672. */
  101673. set: function (elevation) {
  101674. this._defaultElevation = elevation;
  101675. },
  101676. enumerable: true,
  101677. configurable: true
  101678. });
  101679. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  101680. /**
  101681. * Gets the time (in milliseconds) taken to return to the default beta position.
  101682. * Negative value indicates camera should not return to default.
  101683. */
  101684. get: function () {
  101685. return this._elevationReturnTime;
  101686. },
  101687. /**
  101688. * Sets the time (in milliseconds) taken to return to the default beta position.
  101689. * Negative value indicates camera should not return to default.
  101690. */
  101691. set: function (speed) {
  101692. this._elevationReturnTime = speed;
  101693. },
  101694. enumerable: true,
  101695. configurable: true
  101696. });
  101697. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  101698. /**
  101699. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  101700. */
  101701. get: function () {
  101702. return this._elevationReturnWaitTime;
  101703. },
  101704. /**
  101705. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  101706. */
  101707. set: function (time) {
  101708. this._elevationReturnWaitTime = time;
  101709. },
  101710. enumerable: true,
  101711. configurable: true
  101712. });
  101713. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  101714. /**
  101715. * Gets the flag that indicates if user zooming should stop animation.
  101716. */
  101717. get: function () {
  101718. return this._zoomStopsAnimation;
  101719. },
  101720. /**
  101721. * Sets the flag that indicates if user zooming should stop animation.
  101722. */
  101723. set: function (flag) {
  101724. this._zoomStopsAnimation = flag;
  101725. },
  101726. enumerable: true,
  101727. configurable: true
  101728. });
  101729. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  101730. /**
  101731. * Gets the transition time when framing the mesh, in milliseconds
  101732. */
  101733. get: function () {
  101734. return this._framingTime;
  101735. },
  101736. /**
  101737. * Sets the transition time when framing the mesh, in milliseconds
  101738. */
  101739. set: function (time) {
  101740. this._framingTime = time;
  101741. },
  101742. enumerable: true,
  101743. configurable: true
  101744. });
  101745. FramingBehavior.prototype.init = function () {
  101746. // Do notihng
  101747. };
  101748. FramingBehavior.prototype.attach = function (camera) {
  101749. var _this = this;
  101750. this._attachedCamera = camera;
  101751. var scene = this._attachedCamera.getScene();
  101752. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  101753. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101754. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101755. _this._isPointerDown = true;
  101756. return;
  101757. }
  101758. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101759. _this._isPointerDown = false;
  101760. }
  101761. });
  101762. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  101763. if (mesh) {
  101764. _this.zoomOnMesh(mesh);
  101765. }
  101766. });
  101767. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101768. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101769. _this._applyUserInteraction();
  101770. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  101771. // back to the default position after a given timeout
  101772. _this._maintainCameraAboveGround();
  101773. });
  101774. };
  101775. FramingBehavior.prototype.detach = function () {
  101776. if (!this._attachedCamera) {
  101777. return;
  101778. }
  101779. var scene = this._attachedCamera.getScene();
  101780. if (this._onPrePointerObservableObserver) {
  101781. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101782. }
  101783. if (this._onAfterCheckInputsObserver) {
  101784. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101785. }
  101786. if (this._onMeshTargetChangedObserver) {
  101787. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  101788. }
  101789. this._attachedCamera = null;
  101790. };
  101791. /**
  101792. * Targets the given mesh and updates zoom level accordingly.
  101793. * @param mesh The mesh to target.
  101794. * @param radius Optional. If a cached radius position already exists, overrides default.
  101795. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101796. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101797. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101798. */
  101799. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  101800. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101801. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101802. mesh.computeWorldMatrix(true);
  101803. var boundingBox = mesh.getBoundingInfo().boundingBox;
  101804. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  101805. };
  101806. /**
  101807. * Targets the given mesh with its children and updates zoom level accordingly.
  101808. * @param mesh The mesh to target.
  101809. * @param radius Optional. If a cached radius position already exists, overrides default.
  101810. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101811. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101812. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101813. */
  101814. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  101815. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101816. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101817. mesh.computeWorldMatrix(true);
  101818. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  101819. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  101820. };
  101821. /**
  101822. * Targets the given meshes with their children and updates zoom level accordingly.
  101823. * @param meshes The mesh to target.
  101824. * @param radius Optional. If a cached radius position already exists, overrides default.
  101825. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101826. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101827. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101828. */
  101829. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  101830. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101831. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101832. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  101833. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  101834. for (var i = 0; i < meshes.length; i++) {
  101835. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  101836. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  101837. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  101838. }
  101839. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  101840. };
  101841. /**
  101842. * Targets the given mesh and updates zoom level accordingly.
  101843. * @param mesh The mesh to target.
  101844. * @param radius Optional. If a cached radius position already exists, overrides default.
  101845. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  101846. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  101847. * @param onAnimationEnd Callback triggered at the end of the framing animation
  101848. */
  101849. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  101850. var _this = this;
  101851. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  101852. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  101853. var zoomTarget;
  101854. if (!this._attachedCamera) {
  101855. return;
  101856. }
  101857. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  101858. var bottom = minimumWorld.y;
  101859. var top = maximumWorld.y;
  101860. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  101861. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  101862. if (focusOnOriginXZ) {
  101863. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  101864. }
  101865. else {
  101866. var centerWorld = minimumWorld.add(radiusWorld);
  101867. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  101868. }
  101869. if (!this._vectorTransition) {
  101870. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  101871. }
  101872. this._betaIsAnimating = true;
  101873. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  101874. if (animatable) {
  101875. this._animatables.push(animatable);
  101876. }
  101877. // sets the radius and lower radius bounds
  101878. // Small delta ensures camera is not always at lower zoom limit.
  101879. var radius = 0;
  101880. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  101881. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  101882. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  101883. radius = position;
  101884. }
  101885. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  101886. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  101887. if (this._attachedCamera.lowerRadiusLimit === null) {
  101888. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  101889. }
  101890. }
  101891. // Set sensibilities
  101892. var extend = maximumWorld.subtract(minimumWorld).length();
  101893. this._attachedCamera.panningSensibility = 5000 / extend;
  101894. this._attachedCamera.wheelPrecision = 100 / radius;
  101895. // transition to new radius
  101896. if (!this._radiusTransition) {
  101897. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  101898. }
  101899. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  101900. _this.stopAllAnimations();
  101901. if (onAnimationEnd) {
  101902. onAnimationEnd();
  101903. }
  101904. if (_this._attachedCamera) {
  101905. _this._attachedCamera.storeState();
  101906. }
  101907. });
  101908. if (animatable) {
  101909. this._animatables.push(animatable);
  101910. }
  101911. };
  101912. /**
  101913. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  101914. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  101915. * frustum width.
  101916. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  101917. * to fully enclose the mesh in the viewing frustum.
  101918. */
  101919. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  101920. var size = maximumWorld.subtract(minimumWorld);
  101921. var boxVectorGlobalDiagonal = size.length();
  101922. var frustumSlope = this._getFrustumSlope();
  101923. // Formula for setting distance
  101924. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  101925. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  101926. // Horizon distance
  101927. var radius = radiusWithoutFraming * this._radiusScale;
  101928. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  101929. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  101930. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  101931. var camera = this._attachedCamera;
  101932. if (!camera) {
  101933. return 0;
  101934. }
  101935. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  101936. // Don't exceed the requested limit
  101937. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  101938. }
  101939. // Don't exceed the upper radius limit
  101940. if (camera.upperRadiusLimit) {
  101941. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  101942. }
  101943. return distance;
  101944. };
  101945. /**
  101946. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  101947. * is automatically returned to its default position (expected to be above ground plane).
  101948. */
  101949. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  101950. var _this = this;
  101951. if (this._elevationReturnTime < 0) {
  101952. return;
  101953. }
  101954. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  101955. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  101956. var limitBeta = Math.PI * 0.5;
  101957. // Bring the camera back up if below the ground plane
  101958. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  101959. this._betaIsAnimating = true;
  101960. //Transition to new position
  101961. this.stopAllAnimations();
  101962. if (!this._betaTransition) {
  101963. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  101964. }
  101965. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  101966. _this._clearAnimationLocks();
  101967. _this.stopAllAnimations();
  101968. });
  101969. if (animatabe) {
  101970. this._animatables.push(animatabe);
  101971. }
  101972. }
  101973. };
  101974. /**
  101975. * Returns the frustum slope based on the canvas ratio and camera FOV
  101976. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  101977. */
  101978. FramingBehavior.prototype._getFrustumSlope = function () {
  101979. // Calculate the viewport ratio
  101980. // Aspect Ratio is Height/Width.
  101981. var camera = this._attachedCamera;
  101982. if (!camera) {
  101983. return BABYLON.Vector2.Zero();
  101984. }
  101985. var engine = camera.getScene().getEngine();
  101986. var aspectRatio = engine.getAspectRatio(camera);
  101987. // Camera FOV is the vertical field of view (top-bottom) in radians.
  101988. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  101989. var frustumSlopeY = Math.tan(camera.fov / 2);
  101990. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  101991. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  101992. // along the forward vector.
  101993. var frustumSlopeX = frustumSlopeY * aspectRatio;
  101994. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  101995. };
  101996. /**
  101997. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  101998. */
  101999. FramingBehavior.prototype._clearAnimationLocks = function () {
  102000. this._betaIsAnimating = false;
  102001. };
  102002. /**
  102003. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  102004. */
  102005. FramingBehavior.prototype._applyUserInteraction = function () {
  102006. if (this.isUserIsMoving) {
  102007. this._lastInteractionTime = BABYLON.Tools.Now;
  102008. this.stopAllAnimations();
  102009. this._clearAnimationLocks();
  102010. }
  102011. };
  102012. /**
  102013. * Stops and removes all animations that have been applied to the camera
  102014. */
  102015. FramingBehavior.prototype.stopAllAnimations = function () {
  102016. if (this._attachedCamera) {
  102017. this._attachedCamera.animations = [];
  102018. }
  102019. while (this._animatables.length) {
  102020. if (this._animatables[0]) {
  102021. this._animatables[0].onAnimationEnd = null;
  102022. this._animatables[0].stop();
  102023. }
  102024. this._animatables.shift();
  102025. }
  102026. };
  102027. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  102028. /**
  102029. * Gets a value indicating if the user is moving the camera
  102030. */
  102031. get: function () {
  102032. if (!this._attachedCamera) {
  102033. return false;
  102034. }
  102035. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  102036. this._attachedCamera.inertialBetaOffset !== 0 ||
  102037. this._attachedCamera.inertialRadiusOffset !== 0 ||
  102038. this._attachedCamera.inertialPanningX !== 0 ||
  102039. this._attachedCamera.inertialPanningY !== 0 ||
  102040. this._isPointerDown;
  102041. },
  102042. enumerable: true,
  102043. configurable: true
  102044. });
  102045. /**
  102046. * The easing function used by animations
  102047. */
  102048. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  102049. /**
  102050. * The easing mode used by animations
  102051. */
  102052. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  102053. // Statics
  102054. /**
  102055. * The camera can move all the way towards the mesh.
  102056. */
  102057. FramingBehavior.IgnoreBoundsSizeMode = 0;
  102058. /**
  102059. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  102060. */
  102061. FramingBehavior.FitFrustumSidesMode = 1;
  102062. return FramingBehavior;
  102063. }());
  102064. BABYLON.FramingBehavior = FramingBehavior;
  102065. })(BABYLON || (BABYLON = {}));
  102066. //# sourceMappingURL=babylon.framingBehavior.js.map
  102067. var BABYLON;
  102068. (function (BABYLON) {
  102069. /**
  102070. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  102071. */
  102072. var BouncingBehavior = /** @class */ (function () {
  102073. function BouncingBehavior() {
  102074. /**
  102075. * The duration of the animation, in milliseconds
  102076. */
  102077. this.transitionDuration = 450;
  102078. /**
  102079. * Length of the distance animated by the transition when lower radius is reached
  102080. */
  102081. this.lowerRadiusTransitionRange = 2;
  102082. /**
  102083. * Length of the distance animated by the transition when upper radius is reached
  102084. */
  102085. this.upperRadiusTransitionRange = -2;
  102086. this._autoTransitionRange = false;
  102087. // Animations
  102088. this._radiusIsAnimating = false;
  102089. this._radiusBounceTransition = null;
  102090. this._animatables = new Array();
  102091. }
  102092. Object.defineProperty(BouncingBehavior.prototype, "name", {
  102093. get: function () {
  102094. return "Bouncing";
  102095. },
  102096. enumerable: true,
  102097. configurable: true
  102098. });
  102099. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  102100. /**
  102101. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  102102. */
  102103. get: function () {
  102104. return this._autoTransitionRange;
  102105. },
  102106. /**
  102107. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  102108. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  102109. */
  102110. set: function (value) {
  102111. var _this = this;
  102112. if (this._autoTransitionRange === value) {
  102113. return;
  102114. }
  102115. this._autoTransitionRange = value;
  102116. var camera = this._attachedCamera;
  102117. if (!camera) {
  102118. return;
  102119. }
  102120. if (value) {
  102121. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  102122. if (!mesh) {
  102123. return;
  102124. }
  102125. mesh.computeWorldMatrix(true);
  102126. var diagonal = mesh.getBoundingInfo().diagonalLength;
  102127. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  102128. _this.upperRadiusTransitionRange = diagonal * 0.05;
  102129. });
  102130. }
  102131. else if (this._onMeshTargetChangedObserver) {
  102132. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  102133. }
  102134. },
  102135. enumerable: true,
  102136. configurable: true
  102137. });
  102138. BouncingBehavior.prototype.init = function () {
  102139. // Do notihng
  102140. };
  102141. BouncingBehavior.prototype.attach = function (camera) {
  102142. var _this = this;
  102143. this._attachedCamera = camera;
  102144. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  102145. if (!_this._attachedCamera) {
  102146. return;
  102147. }
  102148. // Add the bounce animation to the lower radius limit
  102149. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  102150. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  102151. }
  102152. // Add the bounce animation to the upper radius limit
  102153. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  102154. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  102155. }
  102156. });
  102157. };
  102158. BouncingBehavior.prototype.detach = function () {
  102159. if (!this._attachedCamera) {
  102160. return;
  102161. }
  102162. if (this._onAfterCheckInputsObserver) {
  102163. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  102164. }
  102165. if (this._onMeshTargetChangedObserver) {
  102166. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  102167. }
  102168. this._attachedCamera = null;
  102169. };
  102170. /**
  102171. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  102172. * @param radiusLimit The limit to check against.
  102173. * @return Bool to indicate if at limit.
  102174. */
  102175. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  102176. if (!this._attachedCamera) {
  102177. return false;
  102178. }
  102179. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  102180. return true;
  102181. }
  102182. return false;
  102183. };
  102184. /**
  102185. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  102186. * @param radiusDelta The delta by which to animate to. Can be negative.
  102187. */
  102188. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  102189. var _this = this;
  102190. if (!this._attachedCamera) {
  102191. return;
  102192. }
  102193. if (!this._radiusBounceTransition) {
  102194. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  102195. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  102196. }
  102197. // Prevent zoom until bounce has completed
  102198. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  102199. this._attachedCamera.wheelPrecision = Infinity;
  102200. this._attachedCamera.inertialRadiusOffset = 0;
  102201. // Animate to the radius limit
  102202. this.stopAllAnimations();
  102203. this._radiusIsAnimating = true;
  102204. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  102205. if (animatable) {
  102206. this._animatables.push(animatable);
  102207. }
  102208. };
  102209. /**
  102210. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  102211. */
  102212. BouncingBehavior.prototype._clearAnimationLocks = function () {
  102213. this._radiusIsAnimating = false;
  102214. if (this._attachedCamera) {
  102215. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  102216. }
  102217. };
  102218. /**
  102219. * Stops and removes all animations that have been applied to the camera
  102220. */
  102221. BouncingBehavior.prototype.stopAllAnimations = function () {
  102222. if (this._attachedCamera) {
  102223. this._attachedCamera.animations = [];
  102224. }
  102225. while (this._animatables.length) {
  102226. this._animatables[0].onAnimationEnd = null;
  102227. this._animatables[0].stop();
  102228. this._animatables.shift();
  102229. }
  102230. };
  102231. /**
  102232. * The easing function used by animations
  102233. */
  102234. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  102235. /**
  102236. * The easing mode used by animations
  102237. */
  102238. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  102239. return BouncingBehavior;
  102240. }());
  102241. BABYLON.BouncingBehavior = BouncingBehavior;
  102242. })(BABYLON || (BABYLON = {}));
  102243. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  102244. var BABYLON;
  102245. (function (BABYLON) {
  102246. var AutoRotationBehavior = /** @class */ (function () {
  102247. function AutoRotationBehavior() {
  102248. this._zoomStopsAnimation = false;
  102249. this._idleRotationSpeed = 0.05;
  102250. this._idleRotationWaitTime = 2000;
  102251. this._idleRotationSpinupTime = 2000;
  102252. this._isPointerDown = false;
  102253. this._lastFrameTime = null;
  102254. this._lastInteractionTime = -Infinity;
  102255. this._cameraRotationSpeed = 0;
  102256. this._lastFrameRadius = 0;
  102257. }
  102258. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  102259. get: function () {
  102260. return "AutoRotation";
  102261. },
  102262. enumerable: true,
  102263. configurable: true
  102264. });
  102265. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  102266. /**
  102267. * Gets the flag that indicates if user zooming should stop animation.
  102268. */
  102269. get: function () {
  102270. return this._zoomStopsAnimation;
  102271. },
  102272. /**
  102273. * Sets the flag that indicates if user zooming should stop animation.
  102274. */
  102275. set: function (flag) {
  102276. this._zoomStopsAnimation = flag;
  102277. },
  102278. enumerable: true,
  102279. configurable: true
  102280. });
  102281. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  102282. /**
  102283. * Gets the default speed at which the camera rotates around the model.
  102284. */
  102285. get: function () {
  102286. return this._idleRotationSpeed;
  102287. },
  102288. /**
  102289. * Sets the default speed at which the camera rotates around the model.
  102290. */
  102291. set: function (speed) {
  102292. this._idleRotationSpeed = speed;
  102293. },
  102294. enumerable: true,
  102295. configurable: true
  102296. });
  102297. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  102298. /**
  102299. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  102300. */
  102301. get: function () {
  102302. return this._idleRotationWaitTime;
  102303. },
  102304. /**
  102305. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  102306. */
  102307. set: function (time) {
  102308. this._idleRotationWaitTime = time;
  102309. },
  102310. enumerable: true,
  102311. configurable: true
  102312. });
  102313. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  102314. /**
  102315. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  102316. */
  102317. get: function () {
  102318. return this._idleRotationSpinupTime;
  102319. },
  102320. /**
  102321. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  102322. */
  102323. set: function (time) {
  102324. this._idleRotationSpinupTime = time;
  102325. },
  102326. enumerable: true,
  102327. configurable: true
  102328. });
  102329. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  102330. /**
  102331. * Gets a value indicating if the camera is currently rotating because of this behavior
  102332. */
  102333. get: function () {
  102334. return Math.abs(this._cameraRotationSpeed) > 0;
  102335. },
  102336. enumerable: true,
  102337. configurable: true
  102338. });
  102339. AutoRotationBehavior.prototype.init = function () {
  102340. // Do notihng
  102341. };
  102342. AutoRotationBehavior.prototype.attach = function (camera) {
  102343. var _this = this;
  102344. this._attachedCamera = camera;
  102345. var scene = this._attachedCamera.getScene();
  102346. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  102347. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  102348. _this._isPointerDown = true;
  102349. return;
  102350. }
  102351. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  102352. _this._isPointerDown = false;
  102353. }
  102354. });
  102355. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  102356. var now = BABYLON.Tools.Now;
  102357. var dt = 0;
  102358. if (_this._lastFrameTime != null) {
  102359. dt = now - _this._lastFrameTime;
  102360. }
  102361. _this._lastFrameTime = now;
  102362. // Stop the animation if there is user interaction and the animation should stop for this interaction
  102363. _this._applyUserInteraction();
  102364. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  102365. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  102366. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  102367. // Step camera rotation by rotation speed
  102368. if (_this._attachedCamera) {
  102369. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  102370. }
  102371. });
  102372. };
  102373. AutoRotationBehavior.prototype.detach = function () {
  102374. if (!this._attachedCamera) {
  102375. return;
  102376. }
  102377. var scene = this._attachedCamera.getScene();
  102378. if (this._onPrePointerObservableObserver) {
  102379. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  102380. }
  102381. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  102382. this._attachedCamera = null;
  102383. };
  102384. /**
  102385. * Returns true if user is scrolling.
  102386. * @return true if user is scrolling.
  102387. */
  102388. AutoRotationBehavior.prototype._userIsZooming = function () {
  102389. if (!this._attachedCamera) {
  102390. return false;
  102391. }
  102392. return this._attachedCamera.inertialRadiusOffset !== 0;
  102393. };
  102394. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  102395. if (!this._attachedCamera) {
  102396. return false;
  102397. }
  102398. var zoomHasHitLimit = false;
  102399. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  102400. zoomHasHitLimit = true;
  102401. }
  102402. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  102403. this._lastFrameRadius = this._attachedCamera.radius;
  102404. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  102405. };
  102406. /**
  102407. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  102408. */
  102409. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  102410. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  102411. this._lastInteractionTime = BABYLON.Tools.Now;
  102412. }
  102413. };
  102414. // Tools
  102415. AutoRotationBehavior.prototype._userIsMoving = function () {
  102416. if (!this._attachedCamera) {
  102417. return false;
  102418. }
  102419. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  102420. this._attachedCamera.inertialBetaOffset !== 0 ||
  102421. this._attachedCamera.inertialRadiusOffset !== 0 ||
  102422. this._attachedCamera.inertialPanningX !== 0 ||
  102423. this._attachedCamera.inertialPanningY !== 0 ||
  102424. this._isPointerDown;
  102425. };
  102426. return AutoRotationBehavior;
  102427. }());
  102428. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  102429. })(BABYLON || (BABYLON = {}));
  102430. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  102431. var BABYLON;
  102432. (function (BABYLON) {
  102433. var NullEngineOptions = /** @class */ (function () {
  102434. function NullEngineOptions() {
  102435. this.renderWidth = 512;
  102436. this.renderHeight = 256;
  102437. this.textureSize = 512;
  102438. this.deterministicLockstep = false;
  102439. this.lockstepMaxSteps = 4;
  102440. }
  102441. return NullEngineOptions;
  102442. }());
  102443. BABYLON.NullEngineOptions = NullEngineOptions;
  102444. /**
  102445. * The null engine class provides support for headless version of babylon.js.
  102446. * This can be used in server side scenario or for testing purposes
  102447. */
  102448. var NullEngine = /** @class */ (function (_super) {
  102449. __extends(NullEngine, _super);
  102450. function NullEngine(options) {
  102451. if (options === void 0) { options = new NullEngineOptions(); }
  102452. var _this = _super.call(this, null) || this;
  102453. if (options.deterministicLockstep === undefined) {
  102454. options.deterministicLockstep = false;
  102455. }
  102456. if (options.lockstepMaxSteps === undefined) {
  102457. options.lockstepMaxSteps = 4;
  102458. }
  102459. _this._options = options;
  102460. // Init caps
  102461. // We consider we are on a webgl1 capable device
  102462. _this._caps = new BABYLON.EngineCapabilities();
  102463. _this._caps.maxTexturesImageUnits = 16;
  102464. _this._caps.maxVertexTextureImageUnits = 16;
  102465. _this._caps.maxTextureSize = 512;
  102466. _this._caps.maxCubemapTextureSize = 512;
  102467. _this._caps.maxRenderTextureSize = 512;
  102468. _this._caps.maxVertexAttribs = 16;
  102469. _this._caps.maxVaryingVectors = 16;
  102470. _this._caps.maxFragmentUniformVectors = 16;
  102471. _this._caps.maxVertexUniformVectors = 16;
  102472. // Extensions
  102473. _this._caps.standardDerivatives = false;
  102474. _this._caps.astc = null;
  102475. _this._caps.s3tc = null;
  102476. _this._caps.pvrtc = null;
  102477. _this._caps.etc1 = null;
  102478. _this._caps.etc2 = null;
  102479. _this._caps.textureAnisotropicFilterExtension = null;
  102480. _this._caps.maxAnisotropy = 0;
  102481. _this._caps.uintIndices = false;
  102482. _this._caps.fragmentDepthSupported = false;
  102483. _this._caps.highPrecisionShaderSupported = true;
  102484. _this._caps.colorBufferFloat = false;
  102485. _this._caps.textureFloat = false;
  102486. _this._caps.textureFloatLinearFiltering = false;
  102487. _this._caps.textureFloatRender = false;
  102488. _this._caps.textureHalfFloat = false;
  102489. _this._caps.textureHalfFloatLinearFiltering = false;
  102490. _this._caps.textureHalfFloatRender = false;
  102491. _this._caps.textureLOD = false;
  102492. _this._caps.drawBuffersExtension = false;
  102493. _this._caps.depthTextureExtension = false;
  102494. _this._caps.vertexArrayObject = false;
  102495. _this._caps.instancedArrays = false;
  102496. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  102497. // Wrappers
  102498. if (typeof URL === "undefined") {
  102499. URL = {
  102500. createObjectURL: function () { },
  102501. revokeObjectURL: function () { }
  102502. };
  102503. }
  102504. if (typeof Blob === "undefined") {
  102505. Blob = function () { };
  102506. }
  102507. return _this;
  102508. }
  102509. NullEngine.prototype.isDeterministicLockStep = function () {
  102510. return this._options.deterministicLockstep;
  102511. };
  102512. NullEngine.prototype.getLockstepMaxSteps = function () {
  102513. return this._options.lockstepMaxSteps;
  102514. };
  102515. NullEngine.prototype.getHardwareScalingLevel = function () {
  102516. return 1.0;
  102517. };
  102518. NullEngine.prototype.createVertexBuffer = function (vertices) {
  102519. return {
  102520. capacity: 0,
  102521. references: 1,
  102522. is32Bits: false
  102523. };
  102524. };
  102525. NullEngine.prototype.createIndexBuffer = function (indices) {
  102526. return {
  102527. capacity: 0,
  102528. references: 1,
  102529. is32Bits: false
  102530. };
  102531. };
  102532. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  102533. if (stencil === void 0) { stencil = false; }
  102534. };
  102535. NullEngine.prototype.getRenderWidth = function (useScreen) {
  102536. if (useScreen === void 0) { useScreen = false; }
  102537. if (!useScreen && this._currentRenderTarget) {
  102538. return this._currentRenderTarget.width;
  102539. }
  102540. return this._options.renderWidth;
  102541. };
  102542. NullEngine.prototype.getRenderHeight = function (useScreen) {
  102543. if (useScreen === void 0) { useScreen = false; }
  102544. if (!useScreen && this._currentRenderTarget) {
  102545. return this._currentRenderTarget.height;
  102546. }
  102547. return this._options.renderHeight;
  102548. };
  102549. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  102550. this._cachedViewport = viewport;
  102551. };
  102552. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  102553. return {
  102554. transformFeedback: null,
  102555. __SPECTOR_rebuildProgram: null
  102556. };
  102557. };
  102558. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  102559. return [];
  102560. };
  102561. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  102562. return [];
  102563. };
  102564. NullEngine.prototype.bindSamplers = function (effect) {
  102565. this._currentEffect = null;
  102566. };
  102567. NullEngine.prototype.enableEffect = function (effect) {
  102568. this._currentEffect = effect;
  102569. if (effect.onBind) {
  102570. effect.onBind(effect);
  102571. }
  102572. if (effect._onBindObservable) {
  102573. effect._onBindObservable.notifyObservers(effect);
  102574. }
  102575. };
  102576. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  102577. if (zOffset === void 0) { zOffset = 0; }
  102578. if (reverseSide === void 0) { reverseSide = false; }
  102579. };
  102580. NullEngine.prototype.setIntArray = function (uniform, array) {
  102581. };
  102582. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  102583. };
  102584. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  102585. };
  102586. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  102587. };
  102588. NullEngine.prototype.setFloatArray = function (uniform, array) {
  102589. };
  102590. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  102591. };
  102592. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  102593. };
  102594. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  102595. };
  102596. NullEngine.prototype.setArray = function (uniform, array) {
  102597. };
  102598. NullEngine.prototype.setArray2 = function (uniform, array) {
  102599. };
  102600. NullEngine.prototype.setArray3 = function (uniform, array) {
  102601. };
  102602. NullEngine.prototype.setArray4 = function (uniform, array) {
  102603. };
  102604. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  102605. };
  102606. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  102607. };
  102608. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  102609. };
  102610. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  102611. };
  102612. NullEngine.prototype.setFloat = function (uniform, value) {
  102613. };
  102614. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  102615. };
  102616. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  102617. };
  102618. NullEngine.prototype.setBool = function (uniform, bool) {
  102619. };
  102620. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  102621. };
  102622. NullEngine.prototype.setColor3 = function (uniform, color3) {
  102623. };
  102624. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  102625. };
  102626. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  102627. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  102628. if (this._alphaMode === mode) {
  102629. return;
  102630. }
  102631. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  102632. if (!noDepthWriteChange) {
  102633. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  102634. }
  102635. this._alphaMode = mode;
  102636. };
  102637. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  102638. };
  102639. NullEngine.prototype.wipeCaches = function (bruteForce) {
  102640. if (this.preventCacheWipeBetweenFrames) {
  102641. return;
  102642. }
  102643. this.resetTextureCache();
  102644. this._currentEffect = null;
  102645. if (bruteForce) {
  102646. this._currentProgram = null;
  102647. this._stencilState.reset();
  102648. this._depthCullingState.reset();
  102649. this._alphaState.reset();
  102650. }
  102651. this._cachedVertexBuffers = null;
  102652. this._cachedIndexBuffer = null;
  102653. this._cachedEffectForVertexBuffers = null;
  102654. };
  102655. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  102656. };
  102657. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  102658. };
  102659. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  102660. };
  102661. /** @hidden */
  102662. NullEngine.prototype._createTexture = function () {
  102663. return {};
  102664. };
  102665. /** @hidden */
  102666. NullEngine.prototype._releaseTexture = function (texture) {
  102667. };
  102668. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  102669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102670. if (onLoad === void 0) { onLoad = null; }
  102671. if (onError === void 0) { onError = null; }
  102672. if (buffer === void 0) { buffer = null; }
  102673. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  102674. var url = String(urlArg);
  102675. texture.url = url;
  102676. texture.generateMipMaps = !noMipmap;
  102677. texture.samplingMode = samplingMode;
  102678. texture.invertY = invertY;
  102679. texture.baseWidth = this._options.textureSize;
  102680. texture.baseHeight = this._options.textureSize;
  102681. texture.width = this._options.textureSize;
  102682. texture.height = this._options.textureSize;
  102683. if (format) {
  102684. texture.format = format;
  102685. }
  102686. texture.isReady = true;
  102687. if (onLoad) {
  102688. onLoad();
  102689. }
  102690. this._internalTexturesCache.push(texture);
  102691. return texture;
  102692. };
  102693. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  102694. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  102695. if (options !== undefined && typeof options === "object") {
  102696. fullOptions.generateMipMaps = options.generateMipMaps;
  102697. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  102698. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  102699. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  102700. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  102701. }
  102702. else {
  102703. fullOptions.generateMipMaps = options;
  102704. fullOptions.generateDepthBuffer = true;
  102705. fullOptions.generateStencilBuffer = false;
  102706. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102707. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  102708. }
  102709. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  102710. var width = size.width || size;
  102711. var height = size.height || size;
  102712. texture._depthStencilBuffer = {};
  102713. texture._framebuffer = {};
  102714. texture.baseWidth = width;
  102715. texture.baseHeight = height;
  102716. texture.width = width;
  102717. texture.height = height;
  102718. texture.isReady = true;
  102719. texture.samples = 1;
  102720. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  102721. texture.samplingMode = fullOptions.samplingMode;
  102722. texture.type = fullOptions.type;
  102723. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  102724. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  102725. this._internalTexturesCache.push(texture);
  102726. return texture;
  102727. };
  102728. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  102729. texture.samplingMode = samplingMode;
  102730. };
  102731. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  102732. if (this._currentRenderTarget) {
  102733. this.unBindFramebuffer(this._currentRenderTarget);
  102734. }
  102735. this._currentRenderTarget = texture;
  102736. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  102737. if (this._cachedViewport && !forceFullscreenViewport) {
  102738. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  102739. }
  102740. };
  102741. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  102742. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  102743. this._currentRenderTarget = null;
  102744. if (onBeforeUnbind) {
  102745. if (texture._MSAAFramebuffer) {
  102746. this._currentFramebuffer = texture._framebuffer;
  102747. }
  102748. onBeforeUnbind();
  102749. }
  102750. this._currentFramebuffer = null;
  102751. };
  102752. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  102753. var vbo = {
  102754. capacity: 1,
  102755. references: 1,
  102756. is32Bits: false
  102757. };
  102758. return vbo;
  102759. };
  102760. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  102761. if (premulAlpha === void 0) { premulAlpha = false; }
  102762. };
  102763. /**
  102764. * @hidden
  102765. * Get the current error code of the webGL context
  102766. * @returns the error code
  102767. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  102768. */
  102769. NullEngine.prototype.getError = function () {
  102770. return 0;
  102771. };
  102772. /** @hidden */
  102773. NullEngine.prototype._getUnpackAlignement = function () {
  102774. return 1;
  102775. };
  102776. /** @hidden */
  102777. NullEngine.prototype._unpackFlipY = function (value) {
  102778. };
  102779. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  102780. if (offset === void 0) { offset = 0; }
  102781. };
  102782. /**
  102783. * Updates a dynamic vertex buffer.
  102784. * @param vertexBuffer the vertex buffer to update
  102785. * @param data the data used to update the vertex buffer
  102786. * @param byteOffset the byte offset of the data (optional)
  102787. * @param byteLength the byte length of the data (optional)
  102788. */
  102789. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  102790. };
  102791. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  102792. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  102793. this._boundTexturesCache[this._activeChannel] = texture;
  102794. return true;
  102795. }
  102796. return false;
  102797. };
  102798. /** @hidden */
  102799. NullEngine.prototype._bindTexture = function (channel, texture) {
  102800. if (channel < 0) {
  102801. return;
  102802. }
  102803. this._bindTextureDirectly(0, texture);
  102804. };
  102805. /** @hidden */
  102806. NullEngine.prototype._releaseBuffer = function (buffer) {
  102807. buffer.references--;
  102808. if (buffer.references === 0) {
  102809. return true;
  102810. }
  102811. return false;
  102812. };
  102813. NullEngine.prototype.releaseEffects = function () {
  102814. };
  102815. NullEngine.prototype.displayLoadingUI = function () {
  102816. };
  102817. NullEngine.prototype.hideLoadingUI = function () {
  102818. };
  102819. /** @hidden */
  102820. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  102821. if (faceIndex === void 0) { faceIndex = 0; }
  102822. if (lod === void 0) { lod = 0; }
  102823. };
  102824. /** @hidden */
  102825. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  102826. if (faceIndex === void 0) { faceIndex = 0; }
  102827. if (lod === void 0) { lod = 0; }
  102828. };
  102829. /** @hidden */
  102830. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  102831. if (faceIndex === void 0) { faceIndex = 0; }
  102832. if (lod === void 0) { lod = 0; }
  102833. };
  102834. /** @hidden */
  102835. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  102836. if (faceIndex === void 0) { faceIndex = 0; }
  102837. if (lod === void 0) { lod = 0; }
  102838. };
  102839. return NullEngine;
  102840. }(BABYLON.Engine));
  102841. BABYLON.NullEngine = NullEngine;
  102842. })(BABYLON || (BABYLON = {}));
  102843. //# sourceMappingURL=babylon.nullEngine.js.map
  102844. var BABYLON;
  102845. (function (BABYLON) {
  102846. /**
  102847. * This class can be used to get instrumentation data from a Babylon engine
  102848. */
  102849. var EngineInstrumentation = /** @class */ (function () {
  102850. function EngineInstrumentation(engine) {
  102851. this.engine = engine;
  102852. this._captureGPUFrameTime = false;
  102853. this._gpuFrameTime = new BABYLON.PerfCounter();
  102854. this._captureShaderCompilationTime = false;
  102855. this._shaderCompilationTime = new BABYLON.PerfCounter();
  102856. // Observers
  102857. this._onBeginFrameObserver = null;
  102858. this._onEndFrameObserver = null;
  102859. this._onBeforeShaderCompilationObserver = null;
  102860. this._onAfterShaderCompilationObserver = null;
  102861. }
  102862. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  102863. // Properties
  102864. /**
  102865. * Gets the perf counter used for GPU frame time
  102866. */
  102867. get: function () {
  102868. return this._gpuFrameTime;
  102869. },
  102870. enumerable: true,
  102871. configurable: true
  102872. });
  102873. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  102874. /**
  102875. * Gets the GPU frame time capture status
  102876. */
  102877. get: function () {
  102878. return this._captureGPUFrameTime;
  102879. },
  102880. /**
  102881. * Enable or disable the GPU frame time capture
  102882. */
  102883. set: function (value) {
  102884. var _this = this;
  102885. if (value === this._captureGPUFrameTime) {
  102886. return;
  102887. }
  102888. this._captureGPUFrameTime = value;
  102889. if (value) {
  102890. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  102891. if (!_this._gpuFrameTimeToken) {
  102892. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  102893. }
  102894. });
  102895. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  102896. if (!_this._gpuFrameTimeToken) {
  102897. return;
  102898. }
  102899. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  102900. if (time > -1) {
  102901. _this._gpuFrameTimeToken = null;
  102902. _this._gpuFrameTime.fetchNewFrame();
  102903. _this._gpuFrameTime.addCount(time, true);
  102904. }
  102905. });
  102906. }
  102907. else {
  102908. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  102909. this._onBeginFrameObserver = null;
  102910. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  102911. this._onEndFrameObserver = null;
  102912. }
  102913. },
  102914. enumerable: true,
  102915. configurable: true
  102916. });
  102917. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  102918. /**
  102919. * Gets the perf counter used for shader compilation time
  102920. */
  102921. get: function () {
  102922. return this._shaderCompilationTime;
  102923. },
  102924. enumerable: true,
  102925. configurable: true
  102926. });
  102927. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  102928. /**
  102929. * Gets the shader compilation time capture status
  102930. */
  102931. get: function () {
  102932. return this._captureShaderCompilationTime;
  102933. },
  102934. /**
  102935. * Enable or disable the shader compilation time capture
  102936. */
  102937. set: function (value) {
  102938. var _this = this;
  102939. if (value === this._captureShaderCompilationTime) {
  102940. return;
  102941. }
  102942. this._captureShaderCompilationTime = value;
  102943. if (value) {
  102944. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  102945. _this._shaderCompilationTime.fetchNewFrame();
  102946. _this._shaderCompilationTime.beginMonitoring();
  102947. });
  102948. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  102949. _this._shaderCompilationTime.endMonitoring();
  102950. });
  102951. }
  102952. else {
  102953. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  102954. this._onBeforeShaderCompilationObserver = null;
  102955. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  102956. this._onAfterShaderCompilationObserver = null;
  102957. }
  102958. },
  102959. enumerable: true,
  102960. configurable: true
  102961. });
  102962. EngineInstrumentation.prototype.dispose = function () {
  102963. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  102964. this._onBeginFrameObserver = null;
  102965. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  102966. this._onEndFrameObserver = null;
  102967. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  102968. this._onBeforeShaderCompilationObserver = null;
  102969. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  102970. this._onAfterShaderCompilationObserver = null;
  102971. this.engine = null;
  102972. };
  102973. return EngineInstrumentation;
  102974. }());
  102975. BABYLON.EngineInstrumentation = EngineInstrumentation;
  102976. })(BABYLON || (BABYLON = {}));
  102977. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  102978. var BABYLON;
  102979. (function (BABYLON) {
  102980. /**
  102981. * This class can be used to get instrumentation data from a Babylon engine
  102982. */
  102983. var SceneInstrumentation = /** @class */ (function () {
  102984. function SceneInstrumentation(scene) {
  102985. var _this = this;
  102986. this.scene = scene;
  102987. this._captureActiveMeshesEvaluationTime = false;
  102988. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  102989. this._captureRenderTargetsRenderTime = false;
  102990. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  102991. this._captureFrameTime = false;
  102992. this._frameTime = new BABYLON.PerfCounter();
  102993. this._captureRenderTime = false;
  102994. this._renderTime = new BABYLON.PerfCounter();
  102995. this._captureInterFrameTime = false;
  102996. this._interFrameTime = new BABYLON.PerfCounter();
  102997. this._captureParticlesRenderTime = false;
  102998. this._particlesRenderTime = new BABYLON.PerfCounter();
  102999. this._captureSpritesRenderTime = false;
  103000. this._spritesRenderTime = new BABYLON.PerfCounter();
  103001. this._capturePhysicsTime = false;
  103002. this._physicsTime = new BABYLON.PerfCounter();
  103003. this._captureAnimationsTime = false;
  103004. this._animationsTime = new BABYLON.PerfCounter();
  103005. this._captureCameraRenderTime = false;
  103006. this._cameraRenderTime = new BABYLON.PerfCounter();
  103007. // Observers
  103008. this._onBeforeActiveMeshesEvaluationObserver = null;
  103009. this._onAfterActiveMeshesEvaluationObserver = null;
  103010. this._onBeforeRenderTargetsRenderObserver = null;
  103011. this._onAfterRenderTargetsRenderObserver = null;
  103012. this._onAfterRenderObserver = null;
  103013. this._onBeforeDrawPhaseObserver = null;
  103014. this._onAfterDrawPhaseObserver = null;
  103015. this._onBeforeAnimationsObserver = null;
  103016. this._onBeforeParticlesRenderingObserver = null;
  103017. this._onAfterParticlesRenderingObserver = null;
  103018. this._onBeforeSpritesRenderingObserver = null;
  103019. this._onAfterSpritesRenderingObserver = null;
  103020. this._onBeforePhysicsObserver = null;
  103021. this._onAfterPhysicsObserver = null;
  103022. this._onAfterAnimationsObserver = null;
  103023. this._onBeforeCameraRenderObserver = null;
  103024. this._onAfterCameraRenderObserver = null;
  103025. // Before render
  103026. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  103027. if (_this._captureActiveMeshesEvaluationTime) {
  103028. _this._activeMeshesEvaluationTime.fetchNewFrame();
  103029. }
  103030. if (_this._captureRenderTargetsRenderTime) {
  103031. _this._renderTargetsRenderTime.fetchNewFrame();
  103032. }
  103033. if (_this._captureFrameTime) {
  103034. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  103035. _this._frameTime.beginMonitoring();
  103036. }
  103037. if (_this._captureInterFrameTime) {
  103038. _this._interFrameTime.endMonitoring();
  103039. }
  103040. if (_this._captureParticlesRenderTime) {
  103041. _this._particlesRenderTime.fetchNewFrame();
  103042. }
  103043. if (_this._captureSpritesRenderTime) {
  103044. _this._spritesRenderTime.fetchNewFrame();
  103045. }
  103046. if (_this._captureAnimationsTime) {
  103047. _this._animationsTime.beginMonitoring();
  103048. }
  103049. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  103050. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  103051. });
  103052. // After render
  103053. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  103054. if (_this._captureFrameTime) {
  103055. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  103056. _this._frameTime.endMonitoring();
  103057. }
  103058. if (_this._captureRenderTime) {
  103059. _this._renderTime.endMonitoring(false);
  103060. }
  103061. if (_this._captureInterFrameTime) {
  103062. _this._interFrameTime.beginMonitoring();
  103063. }
  103064. });
  103065. }
  103066. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  103067. // Properties
  103068. /**
  103069. * Gets the perf counter used for active meshes evaluation time
  103070. */
  103071. get: function () {
  103072. return this._activeMeshesEvaluationTime;
  103073. },
  103074. enumerable: true,
  103075. configurable: true
  103076. });
  103077. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  103078. /**
  103079. * Gets the active meshes evaluation time capture status
  103080. */
  103081. get: function () {
  103082. return this._captureActiveMeshesEvaluationTime;
  103083. },
  103084. /**
  103085. * Enable or disable the active meshes evaluation time capture
  103086. */
  103087. set: function (value) {
  103088. var _this = this;
  103089. if (value === this._captureActiveMeshesEvaluationTime) {
  103090. return;
  103091. }
  103092. this._captureActiveMeshesEvaluationTime = value;
  103093. if (value) {
  103094. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  103095. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  103096. _this._activeMeshesEvaluationTime.beginMonitoring();
  103097. });
  103098. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  103099. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  103100. _this._activeMeshesEvaluationTime.endMonitoring();
  103101. });
  103102. }
  103103. else {
  103104. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  103105. this._onBeforeActiveMeshesEvaluationObserver = null;
  103106. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  103107. this._onAfterActiveMeshesEvaluationObserver = null;
  103108. }
  103109. },
  103110. enumerable: true,
  103111. configurable: true
  103112. });
  103113. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  103114. /**
  103115. * Gets the perf counter used for render targets render time
  103116. */
  103117. get: function () {
  103118. return this._renderTargetsRenderTime;
  103119. },
  103120. enumerable: true,
  103121. configurable: true
  103122. });
  103123. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  103124. /**
  103125. * Gets the render targets render time capture status
  103126. */
  103127. get: function () {
  103128. return this._captureRenderTargetsRenderTime;
  103129. },
  103130. /**
  103131. * Enable or disable the render targets render time capture
  103132. */
  103133. set: function (value) {
  103134. var _this = this;
  103135. if (value === this._captureRenderTargetsRenderTime) {
  103136. return;
  103137. }
  103138. this._captureRenderTargetsRenderTime = value;
  103139. if (value) {
  103140. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  103141. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  103142. _this._renderTargetsRenderTime.beginMonitoring();
  103143. });
  103144. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  103145. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  103146. _this._renderTargetsRenderTime.endMonitoring(false);
  103147. });
  103148. }
  103149. else {
  103150. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  103151. this._onBeforeRenderTargetsRenderObserver = null;
  103152. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  103153. this._onAfterRenderTargetsRenderObserver = null;
  103154. }
  103155. },
  103156. enumerable: true,
  103157. configurable: true
  103158. });
  103159. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  103160. /**
  103161. * Gets the perf counter used for particles render time
  103162. */
  103163. get: function () {
  103164. return this._particlesRenderTime;
  103165. },
  103166. enumerable: true,
  103167. configurable: true
  103168. });
  103169. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  103170. /**
  103171. * Gets the particles render time capture status
  103172. */
  103173. get: function () {
  103174. return this._captureParticlesRenderTime;
  103175. },
  103176. /**
  103177. * Enable or disable the particles render time capture
  103178. */
  103179. set: function (value) {
  103180. var _this = this;
  103181. if (value === this._captureParticlesRenderTime) {
  103182. return;
  103183. }
  103184. this._captureParticlesRenderTime = value;
  103185. if (value) {
  103186. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  103187. BABYLON.Tools.StartPerformanceCounter("Particles");
  103188. _this._particlesRenderTime.beginMonitoring();
  103189. });
  103190. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  103191. BABYLON.Tools.EndPerformanceCounter("Particles");
  103192. _this._particlesRenderTime.endMonitoring(false);
  103193. });
  103194. }
  103195. else {
  103196. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  103197. this._onBeforeParticlesRenderingObserver = null;
  103198. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  103199. this._onAfterParticlesRenderingObserver = null;
  103200. }
  103201. },
  103202. enumerable: true,
  103203. configurable: true
  103204. });
  103205. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  103206. /**
  103207. * Gets the perf counter used for sprites render time
  103208. */
  103209. get: function () {
  103210. return this._spritesRenderTime;
  103211. },
  103212. enumerable: true,
  103213. configurable: true
  103214. });
  103215. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  103216. /**
  103217. * Gets the sprites render time capture status
  103218. */
  103219. get: function () {
  103220. return this._captureSpritesRenderTime;
  103221. },
  103222. /**
  103223. * Enable or disable the sprites render time capture
  103224. */
  103225. set: function (value) {
  103226. var _this = this;
  103227. if (value === this._captureSpritesRenderTime) {
  103228. return;
  103229. }
  103230. this._captureSpritesRenderTime = value;
  103231. if (value) {
  103232. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  103233. BABYLON.Tools.StartPerformanceCounter("Sprites");
  103234. _this._spritesRenderTime.beginMonitoring();
  103235. });
  103236. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  103237. BABYLON.Tools.EndPerformanceCounter("Sprites");
  103238. _this._spritesRenderTime.endMonitoring(false);
  103239. });
  103240. }
  103241. else {
  103242. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  103243. this._onBeforeSpritesRenderingObserver = null;
  103244. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  103245. this._onAfterSpritesRenderingObserver = null;
  103246. }
  103247. },
  103248. enumerable: true,
  103249. configurable: true
  103250. });
  103251. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  103252. /**
  103253. * Gets the perf counter used for physics time
  103254. */
  103255. get: function () {
  103256. return this._physicsTime;
  103257. },
  103258. enumerable: true,
  103259. configurable: true
  103260. });
  103261. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  103262. /**
  103263. * Gets the physics time capture status
  103264. */
  103265. get: function () {
  103266. return this._capturePhysicsTime;
  103267. },
  103268. /**
  103269. * Enable or disable the physics time capture
  103270. */
  103271. set: function (value) {
  103272. var _this = this;
  103273. if (value === this._capturePhysicsTime) {
  103274. return;
  103275. }
  103276. this._capturePhysicsTime = value;
  103277. if (value) {
  103278. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  103279. BABYLON.Tools.StartPerformanceCounter("Physics");
  103280. _this._physicsTime.beginMonitoring();
  103281. });
  103282. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  103283. BABYLON.Tools.EndPerformanceCounter("Physics");
  103284. _this._physicsTime.endMonitoring();
  103285. });
  103286. }
  103287. else {
  103288. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  103289. this._onBeforePhysicsObserver = null;
  103290. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  103291. this._onAfterPhysicsObserver = null;
  103292. }
  103293. },
  103294. enumerable: true,
  103295. configurable: true
  103296. });
  103297. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  103298. /**
  103299. * Gets the perf counter used for animations time
  103300. */
  103301. get: function () {
  103302. return this._animationsTime;
  103303. },
  103304. enumerable: true,
  103305. configurable: true
  103306. });
  103307. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  103308. /**
  103309. * Gets the animations time capture status
  103310. */
  103311. get: function () {
  103312. return this._captureAnimationsTime;
  103313. },
  103314. /**
  103315. * Enable or disable the animations time capture
  103316. */
  103317. set: function (value) {
  103318. var _this = this;
  103319. if (value === this._captureAnimationsTime) {
  103320. return;
  103321. }
  103322. this._captureAnimationsTime = value;
  103323. if (value) {
  103324. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  103325. _this._animationsTime.endMonitoring();
  103326. });
  103327. }
  103328. else {
  103329. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  103330. this._onAfterAnimationsObserver = null;
  103331. }
  103332. },
  103333. enumerable: true,
  103334. configurable: true
  103335. });
  103336. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  103337. /**
  103338. * Gets the perf counter used for frame time capture
  103339. */
  103340. get: function () {
  103341. return this._frameTime;
  103342. },
  103343. enumerable: true,
  103344. configurable: true
  103345. });
  103346. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  103347. /**
  103348. * Gets the frame time capture status
  103349. */
  103350. get: function () {
  103351. return this._captureFrameTime;
  103352. },
  103353. /**
  103354. * Enable or disable the frame time capture
  103355. */
  103356. set: function (value) {
  103357. this._captureFrameTime = value;
  103358. },
  103359. enumerable: true,
  103360. configurable: true
  103361. });
  103362. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  103363. /**
  103364. * Gets the perf counter used for inter-frames time capture
  103365. */
  103366. get: function () {
  103367. return this._interFrameTime;
  103368. },
  103369. enumerable: true,
  103370. configurable: true
  103371. });
  103372. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  103373. /**
  103374. * Gets the inter-frames time capture status
  103375. */
  103376. get: function () {
  103377. return this._captureInterFrameTime;
  103378. },
  103379. /**
  103380. * Enable or disable the inter-frames time capture
  103381. */
  103382. set: function (value) {
  103383. this._captureInterFrameTime = value;
  103384. },
  103385. enumerable: true,
  103386. configurable: true
  103387. });
  103388. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  103389. /**
  103390. * Gets the perf counter used for render time capture
  103391. */
  103392. get: function () {
  103393. return this._renderTime;
  103394. },
  103395. enumerable: true,
  103396. configurable: true
  103397. });
  103398. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  103399. /**
  103400. * Gets the render time capture status
  103401. */
  103402. get: function () {
  103403. return this._captureRenderTime;
  103404. },
  103405. /**
  103406. * Enable or disable the render time capture
  103407. */
  103408. set: function (value) {
  103409. var _this = this;
  103410. if (value === this._captureRenderTime) {
  103411. return;
  103412. }
  103413. this._captureRenderTime = value;
  103414. if (value) {
  103415. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  103416. _this._renderTime.beginMonitoring();
  103417. BABYLON.Tools.StartPerformanceCounter("Main render");
  103418. });
  103419. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  103420. _this._renderTime.endMonitoring(false);
  103421. BABYLON.Tools.EndPerformanceCounter("Main render");
  103422. });
  103423. }
  103424. else {
  103425. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  103426. this._onBeforeDrawPhaseObserver = null;
  103427. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  103428. this._onAfterDrawPhaseObserver = null;
  103429. }
  103430. },
  103431. enumerable: true,
  103432. configurable: true
  103433. });
  103434. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  103435. /**
  103436. * Gets the perf counter used for camera render time capture
  103437. */
  103438. get: function () {
  103439. return this._cameraRenderTime;
  103440. },
  103441. enumerable: true,
  103442. configurable: true
  103443. });
  103444. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  103445. /**
  103446. * Gets the camera render time capture status
  103447. */
  103448. get: function () {
  103449. return this._captureCameraRenderTime;
  103450. },
  103451. /**
  103452. * Enable or disable the camera render time capture
  103453. */
  103454. set: function (value) {
  103455. var _this = this;
  103456. if (value === this._captureCameraRenderTime) {
  103457. return;
  103458. }
  103459. this._captureCameraRenderTime = value;
  103460. if (value) {
  103461. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  103462. _this._cameraRenderTime.beginMonitoring();
  103463. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  103464. });
  103465. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  103466. _this._cameraRenderTime.endMonitoring(false);
  103467. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  103468. });
  103469. }
  103470. else {
  103471. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  103472. this._onBeforeCameraRenderObserver = null;
  103473. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  103474. this._onAfterCameraRenderObserver = null;
  103475. }
  103476. },
  103477. enumerable: true,
  103478. configurable: true
  103479. });
  103480. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  103481. /**
  103482. * Gets the perf counter used for draw calls
  103483. */
  103484. get: function () {
  103485. return this.scene.getEngine()._drawCalls;
  103486. },
  103487. enumerable: true,
  103488. configurable: true
  103489. });
  103490. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  103491. /**
  103492. * Gets the perf counter used for texture collisions
  103493. */
  103494. get: function () {
  103495. return this.scene.getEngine()._textureCollisions;
  103496. },
  103497. enumerable: true,
  103498. configurable: true
  103499. });
  103500. SceneInstrumentation.prototype.dispose = function () {
  103501. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  103502. this._onAfterRenderObserver = null;
  103503. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  103504. this._onBeforeActiveMeshesEvaluationObserver = null;
  103505. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  103506. this._onAfterActiveMeshesEvaluationObserver = null;
  103507. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  103508. this._onBeforeRenderTargetsRenderObserver = null;
  103509. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  103510. this._onAfterRenderTargetsRenderObserver = null;
  103511. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  103512. this._onBeforeAnimationsObserver = null;
  103513. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  103514. this._onBeforeParticlesRenderingObserver = null;
  103515. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  103516. this._onAfterParticlesRenderingObserver = null;
  103517. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  103518. this._onBeforeSpritesRenderingObserver = null;
  103519. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  103520. this._onAfterSpritesRenderingObserver = null;
  103521. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  103522. this._onBeforeDrawPhaseObserver = null;
  103523. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  103524. this._onAfterDrawPhaseObserver = null;
  103525. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  103526. this._onBeforePhysicsObserver = null;
  103527. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  103528. this._onAfterPhysicsObserver = null;
  103529. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  103530. this._onAfterAnimationsObserver = null;
  103531. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  103532. this._onBeforeCameraRenderObserver = null;
  103533. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  103534. this._onAfterCameraRenderObserver = null;
  103535. this.scene = null;
  103536. };
  103537. return SceneInstrumentation;
  103538. }());
  103539. BABYLON.SceneInstrumentation = SceneInstrumentation;
  103540. })(BABYLON || (BABYLON = {}));
  103541. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  103542. var BABYLON;
  103543. (function (BABYLON) {
  103544. /**
  103545. * @hidden
  103546. **/
  103547. var _TimeToken = /** @class */ (function () {
  103548. function _TimeToken() {
  103549. this._timeElapsedQueryEnded = false;
  103550. }
  103551. return _TimeToken;
  103552. }());
  103553. BABYLON._TimeToken = _TimeToken;
  103554. })(BABYLON || (BABYLON = {}));
  103555. //# sourceMappingURL=babylon.timeToken.js.map
  103556. var BABYLON;
  103557. (function (BABYLON) {
  103558. /**
  103559. * Background material defines definition.
  103560. * @hidden Mainly internal Use
  103561. */
  103562. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  103563. __extends(BackgroundMaterialDefines, _super);
  103564. /**
  103565. * Constructor of the defines.
  103566. */
  103567. function BackgroundMaterialDefines() {
  103568. var _this = _super.call(this) || this;
  103569. /**
  103570. * True if the diffuse texture is in use.
  103571. */
  103572. _this.DIFFUSE = false;
  103573. /**
  103574. * The direct UV channel to use.
  103575. */
  103576. _this.DIFFUSEDIRECTUV = 0;
  103577. /**
  103578. * True if the diffuse texture is in gamma space.
  103579. */
  103580. _this.GAMMADIFFUSE = false;
  103581. /**
  103582. * True if the diffuse texture has opacity in the alpha channel.
  103583. */
  103584. _this.DIFFUSEHASALPHA = false;
  103585. /**
  103586. * True if you want the material to fade to transparent at grazing angle.
  103587. */
  103588. _this.OPACITYFRESNEL = false;
  103589. /**
  103590. * True if an extra blur needs to be added in the reflection.
  103591. */
  103592. _this.REFLECTIONBLUR = false;
  103593. /**
  103594. * True if you want the material to fade to reflection at grazing angle.
  103595. */
  103596. _this.REFLECTIONFRESNEL = false;
  103597. /**
  103598. * True if you want the material to falloff as far as you move away from the scene center.
  103599. */
  103600. _this.REFLECTIONFALLOFF = false;
  103601. /**
  103602. * False if the current Webgl implementation does not support the texture lod extension.
  103603. */
  103604. _this.TEXTURELODSUPPORT = false;
  103605. /**
  103606. * True to ensure the data are premultiplied.
  103607. */
  103608. _this.PREMULTIPLYALPHA = false;
  103609. /**
  103610. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  103611. */
  103612. _this.USERGBCOLOR = false;
  103613. /**
  103614. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  103615. * stays aligned with the desired configuration.
  103616. */
  103617. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  103618. /**
  103619. * True to add noise in order to reduce the banding effect.
  103620. */
  103621. _this.NOISE = false;
  103622. /**
  103623. * is the reflection texture in BGR color scheme?
  103624. * Mainly used to solve a bug in ios10 video tag
  103625. */
  103626. _this.REFLECTIONBGR = false;
  103627. _this.IMAGEPROCESSING = false;
  103628. _this.VIGNETTE = false;
  103629. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  103630. _this.VIGNETTEBLENDMODEOPAQUE = false;
  103631. _this.TONEMAPPING = false;
  103632. _this.TONEMAPPING_ACES = false;
  103633. _this.CONTRAST = false;
  103634. _this.COLORCURVES = false;
  103635. _this.COLORGRADING = false;
  103636. _this.COLORGRADING3D = false;
  103637. _this.SAMPLER3DGREENDEPTH = false;
  103638. _this.SAMPLER3DBGRMAP = false;
  103639. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  103640. _this.EXPOSURE = false;
  103641. // Reflection.
  103642. _this.REFLECTION = false;
  103643. _this.REFLECTIONMAP_3D = false;
  103644. _this.REFLECTIONMAP_SPHERICAL = false;
  103645. _this.REFLECTIONMAP_PLANAR = false;
  103646. _this.REFLECTIONMAP_CUBIC = false;
  103647. _this.REFLECTIONMAP_PROJECTION = false;
  103648. _this.REFLECTIONMAP_SKYBOX = false;
  103649. _this.REFLECTIONMAP_EXPLICIT = false;
  103650. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  103651. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  103652. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  103653. _this.INVERTCUBICMAP = false;
  103654. _this.REFLECTIONMAP_OPPOSITEZ = false;
  103655. _this.LODINREFLECTIONALPHA = false;
  103656. _this.GAMMAREFLECTION = false;
  103657. _this.RGBDREFLECTION = false;
  103658. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  103659. // Default BJS.
  103660. _this.MAINUV1 = false;
  103661. _this.MAINUV2 = false;
  103662. _this.UV1 = false;
  103663. _this.UV2 = false;
  103664. _this.CLIPPLANE = false;
  103665. _this.POINTSIZE = false;
  103666. _this.FOG = false;
  103667. _this.NORMAL = false;
  103668. _this.NUM_BONE_INFLUENCERS = 0;
  103669. _this.BonesPerMesh = 0;
  103670. _this.INSTANCES = false;
  103671. _this.SHADOWFLOAT = false;
  103672. _this.rebuild();
  103673. return _this;
  103674. }
  103675. return BackgroundMaterialDefines;
  103676. }(BABYLON.MaterialDefines));
  103677. /**
  103678. * Background material used to create an efficient environement around your scene.
  103679. */
  103680. var BackgroundMaterial = /** @class */ (function (_super) {
  103681. __extends(BackgroundMaterial, _super);
  103682. /**
  103683. * Instantiates a Background Material in the given scene
  103684. * @param name The friendly name of the material
  103685. * @param scene The scene to add the material to
  103686. */
  103687. function BackgroundMaterial(name, scene) {
  103688. var _this = _super.call(this, name, scene) || this;
  103689. /**
  103690. * Key light Color (multiply against the environement texture)
  103691. */
  103692. _this.primaryColor = BABYLON.Color3.White();
  103693. _this._primaryColorShadowLevel = 0;
  103694. _this._primaryColorHighlightLevel = 0;
  103695. /**
  103696. * Reflection Texture used in the material.
  103697. * Should be author in a specific way for the best result (refer to the documentation).
  103698. */
  103699. _this.reflectionTexture = null;
  103700. /**
  103701. * Reflection Texture level of blur.
  103702. *
  103703. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  103704. * texture twice.
  103705. */
  103706. _this.reflectionBlur = 0;
  103707. /**
  103708. * Diffuse Texture used in the material.
  103709. * Should be author in a specific way for the best result (refer to the documentation).
  103710. */
  103711. _this.diffuseTexture = null;
  103712. _this._shadowLights = null;
  103713. /**
  103714. * Specify the list of lights casting shadow on the material.
  103715. * All scene shadow lights will be included if null.
  103716. */
  103717. _this.shadowLights = null;
  103718. /**
  103719. * Helps adjusting the shadow to a softer level if required.
  103720. * 0 means black shadows and 1 means no shadows.
  103721. */
  103722. _this.shadowLevel = 0;
  103723. /**
  103724. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  103725. * It is usually zero but might be interesting to modify according to your setup.
  103726. */
  103727. _this.sceneCenter = BABYLON.Vector3.Zero();
  103728. /**
  103729. * This helps specifying that the material is falling off to the sky box at grazing angle.
  103730. * This helps ensuring a nice transition when the camera goes under the ground.
  103731. */
  103732. _this.opacityFresnel = true;
  103733. /**
  103734. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  103735. * This helps adding a mirror texture on the ground.
  103736. */
  103737. _this.reflectionFresnel = false;
  103738. /**
  103739. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  103740. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  103741. */
  103742. _this.reflectionFalloffDistance = 0.0;
  103743. /**
  103744. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  103745. */
  103746. _this.reflectionAmount = 1.0;
  103747. /**
  103748. * This specifies the weight of the reflection at grazing angle.
  103749. */
  103750. _this.reflectionReflectance0 = 0.05;
  103751. /**
  103752. * This specifies the weight of the reflection at a perpendicular point of view.
  103753. */
  103754. _this.reflectionReflectance90 = 0.5;
  103755. /**
  103756. * Helps to directly use the maps channels instead of their level.
  103757. */
  103758. _this.useRGBColor = true;
  103759. /**
  103760. * This helps reducing the banding effect that could occur on the background.
  103761. */
  103762. _this.enableNoise = false;
  103763. _this._fovMultiplier = 1.0;
  103764. /**
  103765. * Enable the FOV adjustment feature controlled by fovMultiplier.
  103766. */
  103767. _this.useEquirectangularFOV = false;
  103768. _this._maxSimultaneousLights = 4;
  103769. /**
  103770. * Number of Simultaneous lights allowed on the material.
  103771. */
  103772. _this.maxSimultaneousLights = 4;
  103773. /**
  103774. * Keep track of the image processing observer to allow dispose and replace.
  103775. */
  103776. _this._imageProcessingObserver = null;
  103777. /**
  103778. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  103779. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  103780. */
  103781. _this.switchToBGR = false;
  103782. // Temp values kept as cache in the material.
  103783. _this._renderTargets = new BABYLON.SmartArray(16);
  103784. _this._reflectionControls = BABYLON.Vector4.Zero();
  103785. _this._white = BABYLON.Color3.White();
  103786. _this._primaryShadowColor = BABYLON.Color3.Black();
  103787. _this._primaryHighlightColor = BABYLON.Color3.Black();
  103788. // Setup the default processing configuration to the scene.
  103789. _this._attachImageProcessingConfiguration(null);
  103790. _this.getRenderTargetTextures = function () {
  103791. _this._renderTargets.reset();
  103792. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  103793. _this._renderTargets.push(_this._diffuseTexture);
  103794. }
  103795. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  103796. _this._renderTargets.push(_this._reflectionTexture);
  103797. }
  103798. return _this._renderTargets;
  103799. };
  103800. return _this;
  103801. }
  103802. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  103803. /**
  103804. * Experimental Internal Use Only.
  103805. *
  103806. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  103807. * This acts as a helper to set the primary color to a more "human friendly" value.
  103808. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  103809. * output color as close as possible from the chosen value.
  103810. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  103811. * part of lighting setup.)
  103812. */
  103813. get: function () {
  103814. return this.__perceptualColor;
  103815. },
  103816. set: function (value) {
  103817. this.__perceptualColor = value;
  103818. this._computePrimaryColorFromPerceptualColor();
  103819. this._markAllSubMeshesAsLightsDirty();
  103820. },
  103821. enumerable: true,
  103822. configurable: true
  103823. });
  103824. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  103825. /**
  103826. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  103827. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  103828. */
  103829. get: function () {
  103830. return this._primaryColorShadowLevel;
  103831. },
  103832. set: function (value) {
  103833. this._primaryColorShadowLevel = value;
  103834. this._computePrimaryColors();
  103835. this._markAllSubMeshesAsLightsDirty();
  103836. },
  103837. enumerable: true,
  103838. configurable: true
  103839. });
  103840. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  103841. /**
  103842. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  103843. * The primary color is used at the level chosen to define what the white area would look.
  103844. */
  103845. get: function () {
  103846. return this._primaryColorHighlightLevel;
  103847. },
  103848. set: function (value) {
  103849. this._primaryColorHighlightLevel = value;
  103850. this._computePrimaryColors();
  103851. this._markAllSubMeshesAsLightsDirty();
  103852. },
  103853. enumerable: true,
  103854. configurable: true
  103855. });
  103856. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  103857. /**
  103858. * Sets the reflection reflectance fresnel values according to the default standard
  103859. * empirically know to work well :-)
  103860. */
  103861. set: function (value) {
  103862. var reflectionWeight = value;
  103863. if (reflectionWeight < 0.5) {
  103864. reflectionWeight = reflectionWeight * 2.0;
  103865. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  103866. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  103867. }
  103868. else {
  103869. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  103870. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  103871. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  103872. }
  103873. },
  103874. enumerable: true,
  103875. configurable: true
  103876. });
  103877. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  103878. /**
  103879. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103880. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  103881. * Recommended to be keep at 1.0 except for special cases.
  103882. */
  103883. get: function () {
  103884. return this._fovMultiplier;
  103885. },
  103886. set: function (value) {
  103887. if (isNaN(value)) {
  103888. value = 1.0;
  103889. }
  103890. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  103891. },
  103892. enumerable: true,
  103893. configurable: true
  103894. });
  103895. /**
  103896. * Attaches a new image processing configuration to the PBR Material.
  103897. * @param configuration (if null the scene configuration will be use)
  103898. */
  103899. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  103900. var _this = this;
  103901. if (configuration === this._imageProcessingConfiguration) {
  103902. return;
  103903. }
  103904. // Detaches observer.
  103905. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103906. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103907. }
  103908. // Pick the scene configuration if needed.
  103909. if (!configuration) {
  103910. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  103911. }
  103912. else {
  103913. this._imageProcessingConfiguration = configuration;
  103914. }
  103915. // Attaches observer.
  103916. if (this._imageProcessingConfiguration) {
  103917. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  103918. _this._computePrimaryColorFromPerceptualColor();
  103919. _this._markAllSubMeshesAsImageProcessingDirty();
  103920. });
  103921. }
  103922. };
  103923. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  103924. /**
  103925. * Gets the image processing configuration used either in this material.
  103926. */
  103927. get: function () {
  103928. return this._imageProcessingConfiguration;
  103929. },
  103930. /**
  103931. * Sets the Default image processing configuration used either in the this material.
  103932. *
  103933. * If sets to null, the scene one is in use.
  103934. */
  103935. set: function (value) {
  103936. this._attachImageProcessingConfiguration(value);
  103937. // Ensure the effect will be rebuilt.
  103938. this._markAllSubMeshesAsTexturesDirty();
  103939. },
  103940. enumerable: true,
  103941. configurable: true
  103942. });
  103943. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  103944. /**
  103945. * Gets wether the color curves effect is enabled.
  103946. */
  103947. get: function () {
  103948. return this.imageProcessingConfiguration.colorCurvesEnabled;
  103949. },
  103950. /**
  103951. * Sets wether the color curves effect is enabled.
  103952. */
  103953. set: function (value) {
  103954. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  103955. },
  103956. enumerable: true,
  103957. configurable: true
  103958. });
  103959. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  103960. /**
  103961. * Gets wether the color grading effect is enabled.
  103962. */
  103963. get: function () {
  103964. return this.imageProcessingConfiguration.colorGradingEnabled;
  103965. },
  103966. /**
  103967. * Gets wether the color grading effect is enabled.
  103968. */
  103969. set: function (value) {
  103970. this.imageProcessingConfiguration.colorGradingEnabled = value;
  103971. },
  103972. enumerable: true,
  103973. configurable: true
  103974. });
  103975. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  103976. /**
  103977. * Gets wether tonemapping is enabled or not.
  103978. */
  103979. get: function () {
  103980. return this._imageProcessingConfiguration.toneMappingEnabled;
  103981. },
  103982. /**
  103983. * Sets wether tonemapping is enabled or not
  103984. */
  103985. set: function (value) {
  103986. this._imageProcessingConfiguration.toneMappingEnabled = value;
  103987. },
  103988. enumerable: true,
  103989. configurable: true
  103990. });
  103991. ;
  103992. ;
  103993. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  103994. /**
  103995. * The camera exposure used on this material.
  103996. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  103997. * This corresponds to a photographic exposure.
  103998. */
  103999. get: function () {
  104000. return this._imageProcessingConfiguration.exposure;
  104001. },
  104002. /**
  104003. * The camera exposure used on this material.
  104004. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  104005. * This corresponds to a photographic exposure.
  104006. */
  104007. set: function (value) {
  104008. this._imageProcessingConfiguration.exposure = value;
  104009. },
  104010. enumerable: true,
  104011. configurable: true
  104012. });
  104013. ;
  104014. ;
  104015. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  104016. /**
  104017. * Gets The camera contrast used on this material.
  104018. */
  104019. get: function () {
  104020. return this._imageProcessingConfiguration.contrast;
  104021. },
  104022. /**
  104023. * Sets The camera contrast used on this material.
  104024. */
  104025. set: function (value) {
  104026. this._imageProcessingConfiguration.contrast = value;
  104027. },
  104028. enumerable: true,
  104029. configurable: true
  104030. });
  104031. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  104032. /**
  104033. * Gets the Color Grading 2D Lookup Texture.
  104034. */
  104035. get: function () {
  104036. return this._imageProcessingConfiguration.colorGradingTexture;
  104037. },
  104038. /**
  104039. * Sets the Color Grading 2D Lookup Texture.
  104040. */
  104041. set: function (value) {
  104042. this.imageProcessingConfiguration.colorGradingTexture = value;
  104043. },
  104044. enumerable: true,
  104045. configurable: true
  104046. });
  104047. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  104048. /**
  104049. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  104050. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  104051. * 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;
  104052. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  104053. */
  104054. get: function () {
  104055. return this.imageProcessingConfiguration.colorCurves;
  104056. },
  104057. /**
  104058. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  104059. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  104060. * 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;
  104061. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  104062. */
  104063. set: function (value) {
  104064. this.imageProcessingConfiguration.colorCurves = value;
  104065. },
  104066. enumerable: true,
  104067. configurable: true
  104068. });
  104069. /**
  104070. * The entire material has been created in order to prevent overdraw.
  104071. * @returns false
  104072. */
  104073. BackgroundMaterial.prototype.needAlphaTesting = function () {
  104074. return true;
  104075. };
  104076. /**
  104077. * The entire material has been created in order to prevent overdraw.
  104078. * @returns true if blending is enable
  104079. */
  104080. BackgroundMaterial.prototype.needAlphaBlending = function () {
  104081. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  104082. };
  104083. /**
  104084. * Checks wether the material is ready to be rendered for a given mesh.
  104085. * @param mesh The mesh to render
  104086. * @param subMesh The submesh to check against
  104087. * @param useInstances Specify wether or not the material is used with instances
  104088. * @returns true if all the dependencies are ready (Textures, Effects...)
  104089. */
  104090. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  104091. var _this = this;
  104092. if (useInstances === void 0) { useInstances = false; }
  104093. if (subMesh.effect && this.isFrozen) {
  104094. if (this._wasPreviouslyReady) {
  104095. return true;
  104096. }
  104097. }
  104098. if (!subMesh._materialDefines) {
  104099. subMesh._materialDefines = new BackgroundMaterialDefines();
  104100. }
  104101. var scene = this.getScene();
  104102. var defines = subMesh._materialDefines;
  104103. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  104104. if (defines._renderId === scene.getRenderId()) {
  104105. return true;
  104106. }
  104107. }
  104108. var engine = scene.getEngine();
  104109. // Lights
  104110. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  104111. defines._needNormals = true;
  104112. // Textures
  104113. if (defines._areTexturesDirty) {
  104114. defines._needUVs = false;
  104115. if (scene.texturesEnabled) {
  104116. if (scene.getEngine().getCaps().textureLOD) {
  104117. defines.TEXTURELODSUPPORT = true;
  104118. }
  104119. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  104120. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  104121. return false;
  104122. }
  104123. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  104124. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  104125. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  104126. defines.OPACITYFRESNEL = this._opacityFresnel;
  104127. }
  104128. else {
  104129. defines.DIFFUSE = false;
  104130. defines.DIFFUSEHASALPHA = false;
  104131. defines.GAMMADIFFUSE = false;
  104132. defines.OPACITYFRESNEL = false;
  104133. }
  104134. var reflectionTexture = this._reflectionTexture;
  104135. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  104136. if (!reflectionTexture.isReadyOrNotBlocking()) {
  104137. return false;
  104138. }
  104139. defines.REFLECTION = true;
  104140. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  104141. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  104142. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  104143. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  104144. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  104145. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  104146. defines.REFLECTIONBGR = this.switchToBGR;
  104147. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  104148. defines.INVERTCUBICMAP = true;
  104149. }
  104150. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  104151. switch (reflectionTexture.coordinatesMode) {
  104152. case BABYLON.Texture.EXPLICIT_MODE:
  104153. defines.REFLECTIONMAP_EXPLICIT = true;
  104154. break;
  104155. case BABYLON.Texture.PLANAR_MODE:
  104156. defines.REFLECTIONMAP_PLANAR = true;
  104157. break;
  104158. case BABYLON.Texture.PROJECTION_MODE:
  104159. defines.REFLECTIONMAP_PROJECTION = true;
  104160. break;
  104161. case BABYLON.Texture.SKYBOX_MODE:
  104162. defines.REFLECTIONMAP_SKYBOX = true;
  104163. break;
  104164. case BABYLON.Texture.SPHERICAL_MODE:
  104165. defines.REFLECTIONMAP_SPHERICAL = true;
  104166. break;
  104167. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  104168. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  104169. break;
  104170. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  104171. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  104172. break;
  104173. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  104174. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  104175. break;
  104176. case BABYLON.Texture.CUBIC_MODE:
  104177. case BABYLON.Texture.INVCUBIC_MODE:
  104178. default:
  104179. defines.REFLECTIONMAP_CUBIC = true;
  104180. break;
  104181. }
  104182. if (this.reflectionFresnel) {
  104183. defines.REFLECTIONFRESNEL = true;
  104184. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  104185. this._reflectionControls.x = this.reflectionAmount;
  104186. this._reflectionControls.y = this.reflectionReflectance0;
  104187. this._reflectionControls.z = this.reflectionReflectance90;
  104188. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  104189. }
  104190. else {
  104191. defines.REFLECTIONFRESNEL = false;
  104192. defines.REFLECTIONFALLOFF = false;
  104193. }
  104194. }
  104195. else {
  104196. defines.REFLECTION = false;
  104197. defines.REFLECTIONFRESNEL = false;
  104198. defines.REFLECTIONFALLOFF = false;
  104199. defines.REFLECTIONBLUR = false;
  104200. defines.REFLECTIONMAP_3D = false;
  104201. defines.REFLECTIONMAP_SPHERICAL = false;
  104202. defines.REFLECTIONMAP_PLANAR = false;
  104203. defines.REFLECTIONMAP_CUBIC = false;
  104204. defines.REFLECTIONMAP_PROJECTION = false;
  104205. defines.REFLECTIONMAP_SKYBOX = false;
  104206. defines.REFLECTIONMAP_EXPLICIT = false;
  104207. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  104208. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  104209. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  104210. defines.INVERTCUBICMAP = false;
  104211. defines.REFLECTIONMAP_OPPOSITEZ = false;
  104212. defines.LODINREFLECTIONALPHA = false;
  104213. defines.GAMMAREFLECTION = false;
  104214. defines.RGBDREFLECTION = false;
  104215. }
  104216. }
  104217. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  104218. defines.USERGBCOLOR = this._useRGBColor;
  104219. defines.NOISE = this._enableNoise;
  104220. }
  104221. if (defines._areLightsDirty) {
  104222. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  104223. }
  104224. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  104225. if (!this._imageProcessingConfiguration.isReady()) {
  104226. return false;
  104227. }
  104228. this._imageProcessingConfiguration.prepareDefines(defines);
  104229. }
  104230. // Misc.
  104231. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  104232. // Values that need to be evaluated on every frame
  104233. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  104234. // Attribs
  104235. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  104236. if (mesh) {
  104237. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  104238. mesh.createNormals(true);
  104239. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  104240. }
  104241. }
  104242. }
  104243. // Get correct effect
  104244. if (defines.isDirty) {
  104245. defines.markAsProcessed();
  104246. scene.resetCachedMaterial();
  104247. // Fallbacks
  104248. var fallbacks = new BABYLON.EffectFallbacks();
  104249. if (defines.FOG) {
  104250. fallbacks.addFallback(0, "FOG");
  104251. }
  104252. if (defines.POINTSIZE) {
  104253. fallbacks.addFallback(1, "POINTSIZE");
  104254. }
  104255. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  104256. if (defines.NUM_BONE_INFLUENCERS > 0) {
  104257. fallbacks.addCPUSkinningFallback(0, mesh);
  104258. }
  104259. //Attributes
  104260. var attribs = [BABYLON.VertexBuffer.PositionKind];
  104261. if (defines.NORMAL) {
  104262. attribs.push(BABYLON.VertexBuffer.NormalKind);
  104263. }
  104264. if (defines.UV1) {
  104265. attribs.push(BABYLON.VertexBuffer.UVKind);
  104266. }
  104267. if (defines.UV2) {
  104268. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104269. }
  104270. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  104271. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  104272. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  104273. "vFogInfos", "vFogColor", "pointSize",
  104274. "vClipPlane", "mBones",
  104275. "vPrimaryColor", "vPrimaryColorShadow",
  104276. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  104277. "shadowLevel", "alpha",
  104278. "vBackgroundCenter", "vReflectionControl",
  104279. "vDiffuseInfos", "diffuseMatrix",
  104280. ];
  104281. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  104282. var uniformBuffers = ["Material", "Scene"];
  104283. if (BABYLON.ImageProcessingConfiguration) {
  104284. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  104285. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  104286. }
  104287. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  104288. uniformsNames: uniforms,
  104289. uniformBuffersNames: uniformBuffers,
  104290. samplers: samplers,
  104291. defines: defines,
  104292. maxSimultaneousLights: this._maxSimultaneousLights
  104293. });
  104294. var onCompiled = function (effect) {
  104295. if (_this.onCompiled) {
  104296. _this.onCompiled(effect);
  104297. }
  104298. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  104299. };
  104300. var join = defines.toString();
  104301. subMesh.setEffect(scene.getEngine().createEffect("background", {
  104302. attributes: attribs,
  104303. uniformsNames: uniforms,
  104304. uniformBuffersNames: uniformBuffers,
  104305. samplers: samplers,
  104306. defines: join,
  104307. fallbacks: fallbacks,
  104308. onCompiled: onCompiled,
  104309. onError: this.onError,
  104310. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  104311. }, engine), defines);
  104312. this.buildUniformLayout();
  104313. }
  104314. if (!subMesh.effect || !subMesh.effect.isReady()) {
  104315. return false;
  104316. }
  104317. defines._renderId = scene.getRenderId();
  104318. this._wasPreviouslyReady = true;
  104319. return true;
  104320. };
  104321. /**
  104322. * Compute the primary color according to the chosen perceptual color.
  104323. */
  104324. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  104325. if (!this.__perceptualColor) {
  104326. return;
  104327. }
  104328. this._primaryColor.copyFrom(this.__perceptualColor);
  104329. // Revert gamma space.
  104330. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  104331. // Revert image processing configuration.
  104332. if (this._imageProcessingConfiguration) {
  104333. // Revert Exposure.
  104334. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  104335. }
  104336. this._computePrimaryColors();
  104337. };
  104338. /**
  104339. * Compute the highlights and shadow colors according to their chosen levels.
  104340. */
  104341. BackgroundMaterial.prototype._computePrimaryColors = function () {
  104342. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  104343. return;
  104344. }
  104345. // Find the highlight color based on the configuration.
  104346. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  104347. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  104348. // Find the shadow color based on the configuration.
  104349. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  104350. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  104351. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  104352. };
  104353. /**
  104354. * Build the uniform buffer used in the material.
  104355. */
  104356. BackgroundMaterial.prototype.buildUniformLayout = function () {
  104357. // Order is important !
  104358. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  104359. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  104360. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  104361. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  104362. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  104363. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  104364. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  104365. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  104366. this._uniformBuffer.addUniform("pointSize", 1);
  104367. this._uniformBuffer.addUniform("shadowLevel", 1);
  104368. this._uniformBuffer.addUniform("alpha", 1);
  104369. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  104370. this._uniformBuffer.addUniform("vReflectionControl", 4);
  104371. this._uniformBuffer.create();
  104372. };
  104373. /**
  104374. * Unbind the material.
  104375. */
  104376. BackgroundMaterial.prototype.unbind = function () {
  104377. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  104378. this._uniformBuffer.setTexture("diffuseSampler", null);
  104379. }
  104380. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  104381. this._uniformBuffer.setTexture("reflectionSampler", null);
  104382. }
  104383. _super.prototype.unbind.call(this);
  104384. };
  104385. /**
  104386. * Bind only the world matrix to the material.
  104387. * @param world The world matrix to bind.
  104388. */
  104389. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  104390. this._activeEffect.setMatrix("world", world);
  104391. };
  104392. /**
  104393. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  104394. * @param world The world matrix to bind.
  104395. * @param subMesh The submesh to bind for.
  104396. */
  104397. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  104398. var scene = this.getScene();
  104399. var defines = subMesh._materialDefines;
  104400. if (!defines) {
  104401. return;
  104402. }
  104403. var effect = subMesh.effect;
  104404. if (!effect) {
  104405. return;
  104406. }
  104407. this._activeEffect = effect;
  104408. // Matrices
  104409. this.bindOnlyWorldMatrix(world);
  104410. // Bones
  104411. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  104412. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  104413. if (mustRebind) {
  104414. this._uniformBuffer.bindToEffect(effect, "Material");
  104415. this.bindViewProjection(effect);
  104416. var reflectionTexture = this._reflectionTexture;
  104417. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  104418. // Texture uniforms
  104419. if (scene.texturesEnabled) {
  104420. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  104421. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  104422. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  104423. }
  104424. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  104425. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  104426. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  104427. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  104428. }
  104429. }
  104430. if (this.shadowLevel > 0) {
  104431. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  104432. }
  104433. this._uniformBuffer.updateFloat("alpha", this.alpha);
  104434. // Point size
  104435. if (this.pointsCloud) {
  104436. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  104437. }
  104438. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  104439. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  104440. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  104441. }
  104442. else {
  104443. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  104444. }
  104445. }
  104446. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  104447. // Textures
  104448. if (scene.texturesEnabled) {
  104449. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  104450. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  104451. }
  104452. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  104453. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  104454. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  104455. }
  104456. else if (!defines.REFLECTIONBLUR) {
  104457. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  104458. }
  104459. else {
  104460. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  104461. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  104462. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  104463. }
  104464. if (defines.REFLECTIONFRESNEL) {
  104465. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  104466. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  104467. }
  104468. }
  104469. }
  104470. // Clip plane
  104471. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  104472. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  104473. }
  104474. if (mustRebind || !this.isFrozen) {
  104475. if (scene.lightsEnabled) {
  104476. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  104477. }
  104478. // View
  104479. this.bindView(effect);
  104480. // Fog
  104481. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  104482. // image processing
  104483. if (this._imageProcessingConfiguration) {
  104484. this._imageProcessingConfiguration.bind(this._activeEffect);
  104485. }
  104486. }
  104487. this._uniformBuffer.update();
  104488. this._afterBind(mesh, this._activeEffect);
  104489. };
  104490. /**
  104491. * Dispose the material.
  104492. * @param forceDisposeEffect Force disposal of the associated effect.
  104493. * @param forceDisposeTextures Force disposal of the associated textures.
  104494. */
  104495. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  104496. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  104497. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  104498. if (forceDisposeTextures) {
  104499. if (this.diffuseTexture) {
  104500. this.diffuseTexture.dispose();
  104501. }
  104502. if (this.reflectionTexture) {
  104503. this.reflectionTexture.dispose();
  104504. }
  104505. }
  104506. this._renderTargets.dispose();
  104507. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  104508. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  104509. }
  104510. _super.prototype.dispose.call(this, forceDisposeEffect);
  104511. };
  104512. /**
  104513. * Clones the material.
  104514. * @param name The cloned name.
  104515. * @returns The cloned material.
  104516. */
  104517. BackgroundMaterial.prototype.clone = function (name) {
  104518. var _this = this;
  104519. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  104520. };
  104521. /**
  104522. * Serializes the current material to its JSON representation.
  104523. * @returns The JSON representation.
  104524. */
  104525. BackgroundMaterial.prototype.serialize = function () {
  104526. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  104527. serializationObject.customType = "BABYLON.BackgroundMaterial";
  104528. return serializationObject;
  104529. };
  104530. /**
  104531. * Gets the class name of the material
  104532. * @returns "BackgroundMaterial"
  104533. */
  104534. BackgroundMaterial.prototype.getClassName = function () {
  104535. return "BackgroundMaterial";
  104536. };
  104537. /**
  104538. * Parse a JSON input to create back a background material.
  104539. * @param source The JSON data to parse
  104540. * @param scene The scene to create the parsed material in
  104541. * @param rootUrl The root url of the assets the material depends upon
  104542. * @returns the instantiated BackgroundMaterial.
  104543. */
  104544. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  104545. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  104546. };
  104547. /**
  104548. * Standard reflectance value at parallel view angle.
  104549. */
  104550. BackgroundMaterial.StandardReflectance0 = 0.05;
  104551. /**
  104552. * Standard reflectance value at grazing angle.
  104553. */
  104554. BackgroundMaterial.StandardReflectance90 = 0.5;
  104555. __decorate([
  104556. BABYLON.serializeAsColor3()
  104557. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  104558. __decorate([
  104559. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  104560. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  104561. __decorate([
  104562. BABYLON.serializeAsColor3()
  104563. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  104564. __decorate([
  104565. BABYLON.serialize()
  104566. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  104567. __decorate([
  104568. BABYLON.serialize()
  104569. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  104570. __decorate([
  104571. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  104572. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  104573. __decorate([
  104574. BABYLON.serializeAsTexture()
  104575. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  104576. __decorate([
  104577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104578. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  104579. __decorate([
  104580. BABYLON.serialize()
  104581. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  104582. __decorate([
  104583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104584. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  104585. __decorate([
  104586. BABYLON.serializeAsTexture()
  104587. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  104588. __decorate([
  104589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104590. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  104591. __decorate([
  104592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104593. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  104594. __decorate([
  104595. BABYLON.serialize()
  104596. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  104597. __decorate([
  104598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104599. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  104600. __decorate([
  104601. BABYLON.serializeAsVector3()
  104602. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  104603. __decorate([
  104604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104605. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  104606. __decorate([
  104607. BABYLON.serialize()
  104608. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  104609. __decorate([
  104610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104611. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  104612. __decorate([
  104613. BABYLON.serialize()
  104614. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  104615. __decorate([
  104616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104617. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  104618. __decorate([
  104619. BABYLON.serialize()
  104620. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  104621. __decorate([
  104622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104623. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  104624. __decorate([
  104625. BABYLON.serialize()
  104626. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  104627. __decorate([
  104628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104629. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  104630. __decorate([
  104631. BABYLON.serialize()
  104632. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  104633. __decorate([
  104634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104635. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  104636. __decorate([
  104637. BABYLON.serialize()
  104638. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  104639. __decorate([
  104640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104641. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  104642. __decorate([
  104643. BABYLON.serialize()
  104644. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  104645. __decorate([
  104646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104647. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  104648. __decorate([
  104649. BABYLON.serialize()
  104650. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  104651. __decorate([
  104652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104653. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  104654. __decorate([
  104655. BABYLON.serialize()
  104656. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  104657. __decorate([
  104658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104659. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  104660. __decorate([
  104661. BABYLON.serializeAsImageProcessingConfiguration()
  104662. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  104663. return BackgroundMaterial;
  104664. }(BABYLON.PushMaterial));
  104665. BABYLON.BackgroundMaterial = BackgroundMaterial;
  104666. })(BABYLON || (BABYLON = {}));
  104667. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  104668. var __assign = (this && this.__assign) || Object.assign || function(t) {
  104669. for (var s, i = 1, n = arguments.length; i < n; i++) {
  104670. s = arguments[i];
  104671. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  104672. t[p] = s[p];
  104673. }
  104674. return t;
  104675. };
  104676. var BABYLON;
  104677. (function (BABYLON) {
  104678. /**
  104679. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  104680. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  104681. * It also helps with the default setup of your imageProcessing configuration.
  104682. */
  104683. var EnvironmentHelper = /** @class */ (function () {
  104684. /**
  104685. * constructor
  104686. * @param options
  104687. * @param scene The scene to add the material to
  104688. */
  104689. function EnvironmentHelper(options, scene) {
  104690. var _this = this;
  104691. this._errorHandler = function (message, exception) {
  104692. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  104693. };
  104694. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  104695. this._scene = scene;
  104696. this.onErrorObservable = new BABYLON.Observable();
  104697. this._setupBackground();
  104698. this._setupImageProcessing();
  104699. }
  104700. /**
  104701. * Creates the default options for the helper.
  104702. */
  104703. EnvironmentHelper._getDefaultOptions = function () {
  104704. return {
  104705. createGround: true,
  104706. groundSize: 15,
  104707. groundTexture: this._groundTextureCDNUrl,
  104708. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  104709. groundOpacity: 0.9,
  104710. enableGroundShadow: true,
  104711. groundShadowLevel: 0.5,
  104712. enableGroundMirror: false,
  104713. groundMirrorSizeRatio: 0.3,
  104714. groundMirrorBlurKernel: 64,
  104715. groundMirrorAmount: 1,
  104716. groundMirrorFresnelWeight: 1,
  104717. groundMirrorFallOffDistance: 0,
  104718. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  104719. groundYBias: 0.00001,
  104720. createSkybox: true,
  104721. skyboxSize: 20,
  104722. skyboxTexture: this._skyboxTextureCDNUrl,
  104723. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  104724. backgroundYRotation: 0,
  104725. sizeAuto: true,
  104726. rootPosition: BABYLON.Vector3.Zero(),
  104727. setupImageProcessing: true,
  104728. environmentTexture: this._environmentTextureCDNUrl,
  104729. cameraExposure: 0.8,
  104730. cameraContrast: 1.2,
  104731. toneMappingEnabled: true,
  104732. };
  104733. };
  104734. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  104735. /**
  104736. * Gets the root mesh created by the helper.
  104737. */
  104738. get: function () {
  104739. return this._rootMesh;
  104740. },
  104741. enumerable: true,
  104742. configurable: true
  104743. });
  104744. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  104745. /**
  104746. * Gets the skybox created by the helper.
  104747. */
  104748. get: function () {
  104749. return this._skybox;
  104750. },
  104751. enumerable: true,
  104752. configurable: true
  104753. });
  104754. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  104755. /**
  104756. * Gets the skybox texture created by the helper.
  104757. */
  104758. get: function () {
  104759. return this._skyboxTexture;
  104760. },
  104761. enumerable: true,
  104762. configurable: true
  104763. });
  104764. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  104765. /**
  104766. * Gets the skybox material created by the helper.
  104767. */
  104768. get: function () {
  104769. return this._skyboxMaterial;
  104770. },
  104771. enumerable: true,
  104772. configurable: true
  104773. });
  104774. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  104775. /**
  104776. * Gets the ground mesh created by the helper.
  104777. */
  104778. get: function () {
  104779. return this._ground;
  104780. },
  104781. enumerable: true,
  104782. configurable: true
  104783. });
  104784. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  104785. /**
  104786. * Gets the ground texture created by the helper.
  104787. */
  104788. get: function () {
  104789. return this._groundTexture;
  104790. },
  104791. enumerable: true,
  104792. configurable: true
  104793. });
  104794. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  104795. /**
  104796. * Gets the ground mirror created by the helper.
  104797. */
  104798. get: function () {
  104799. return this._groundMirror;
  104800. },
  104801. enumerable: true,
  104802. configurable: true
  104803. });
  104804. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  104805. /**
  104806. * Gets the ground mirror render list to helps pushing the meshes
  104807. * you wish in the ground reflection.
  104808. */
  104809. get: function () {
  104810. if (this._groundMirror) {
  104811. return this._groundMirror.renderList;
  104812. }
  104813. return null;
  104814. },
  104815. enumerable: true,
  104816. configurable: true
  104817. });
  104818. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  104819. /**
  104820. * Gets the ground material created by the helper.
  104821. */
  104822. get: function () {
  104823. return this._groundMaterial;
  104824. },
  104825. enumerable: true,
  104826. configurable: true
  104827. });
  104828. /**
  104829. * Updates the background according to the new options
  104830. * @param options
  104831. */
  104832. EnvironmentHelper.prototype.updateOptions = function (options) {
  104833. var newOptions = __assign({}, this._options, options);
  104834. if (this._ground && !newOptions.createGround) {
  104835. this._ground.dispose();
  104836. this._ground = null;
  104837. }
  104838. if (this._groundMaterial && !newOptions.createGround) {
  104839. this._groundMaterial.dispose();
  104840. this._groundMaterial = null;
  104841. }
  104842. if (this._groundTexture) {
  104843. if (this._options.groundTexture != newOptions.groundTexture) {
  104844. this._groundTexture.dispose();
  104845. this._groundTexture = null;
  104846. }
  104847. }
  104848. if (this._skybox && !newOptions.createSkybox) {
  104849. this._skybox.dispose();
  104850. this._skybox = null;
  104851. }
  104852. if (this._skyboxMaterial && !newOptions.createSkybox) {
  104853. this._skyboxMaterial.dispose();
  104854. this._skyboxMaterial = null;
  104855. }
  104856. if (this._skyboxTexture) {
  104857. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  104858. this._skyboxTexture.dispose();
  104859. this._skyboxTexture = null;
  104860. }
  104861. }
  104862. if (this._groundMirror && !newOptions.enableGroundMirror) {
  104863. this._groundMirror.dispose();
  104864. this._groundMirror = null;
  104865. }
  104866. if (this._scene.environmentTexture) {
  104867. if (this._options.environmentTexture != newOptions.environmentTexture) {
  104868. this._scene.environmentTexture.dispose();
  104869. }
  104870. }
  104871. this._options = newOptions;
  104872. this._setupBackground();
  104873. this._setupImageProcessing();
  104874. };
  104875. /**
  104876. * Sets the primary color of all the available elements.
  104877. * @param color the main color to affect to the ground and the background
  104878. */
  104879. EnvironmentHelper.prototype.setMainColor = function (color) {
  104880. if (this.groundMaterial) {
  104881. this.groundMaterial.primaryColor = color;
  104882. }
  104883. if (this.skyboxMaterial) {
  104884. this.skyboxMaterial.primaryColor = color;
  104885. }
  104886. if (this.groundMirror) {
  104887. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  104888. }
  104889. };
  104890. /**
  104891. * Setup the image processing according to the specified options.
  104892. */
  104893. EnvironmentHelper.prototype._setupImageProcessing = function () {
  104894. if (this._options.setupImageProcessing) {
  104895. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  104896. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  104897. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  104898. this._setupEnvironmentTexture();
  104899. }
  104900. };
  104901. /**
  104902. * Setup the environment texture according to the specified options.
  104903. */
  104904. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  104905. if (this._scene.environmentTexture) {
  104906. return;
  104907. }
  104908. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  104909. this._scene.environmentTexture = this._options.environmentTexture;
  104910. return;
  104911. }
  104912. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  104913. this._scene.environmentTexture = environmentTexture;
  104914. };
  104915. /**
  104916. * Setup the background according to the specified options.
  104917. */
  104918. EnvironmentHelper.prototype._setupBackground = function () {
  104919. if (!this._rootMesh) {
  104920. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  104921. }
  104922. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  104923. var sceneSize = this._getSceneSize();
  104924. if (this._options.createGround) {
  104925. this._setupGround(sceneSize);
  104926. this._setupGroundMaterial();
  104927. this._setupGroundDiffuseTexture();
  104928. if (this._options.enableGroundMirror) {
  104929. this._setupGroundMirrorTexture(sceneSize);
  104930. }
  104931. this._setupMirrorInGroundMaterial();
  104932. }
  104933. if (this._options.createSkybox) {
  104934. this._setupSkybox(sceneSize);
  104935. this._setupSkyboxMaterial();
  104936. this._setupSkyboxReflectionTexture();
  104937. }
  104938. this._rootMesh.position.x = sceneSize.rootPosition.x;
  104939. this._rootMesh.position.z = sceneSize.rootPosition.z;
  104940. this._rootMesh.position.y = sceneSize.rootPosition.y;
  104941. };
  104942. /**
  104943. * Get the scene sizes according to the setup.
  104944. */
  104945. EnvironmentHelper.prototype._getSceneSize = function () {
  104946. var _this = this;
  104947. var groundSize = this._options.groundSize;
  104948. var skyboxSize = this._options.skyboxSize;
  104949. var rootPosition = this._options.rootPosition;
  104950. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  104951. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  104952. }
  104953. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  104954. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  104955. });
  104956. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  104957. if (this._options.sizeAuto) {
  104958. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  104959. this._scene.activeCamera.upperRadiusLimit) {
  104960. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  104961. skyboxSize = groundSize;
  104962. }
  104963. var sceneDiagonalLenght = sceneDiagonal.length();
  104964. if (sceneDiagonalLenght > groundSize) {
  104965. groundSize = sceneDiagonalLenght * 2;
  104966. skyboxSize = groundSize;
  104967. }
  104968. // 10 % bigger.
  104969. groundSize *= 1.1;
  104970. skyboxSize *= 1.5;
  104971. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  104972. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  104973. }
  104974. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  104975. };
  104976. /**
  104977. * Setup the ground according to the specified options.
  104978. */
  104979. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  104980. var _this = this;
  104981. if (!this._ground || this._ground.isDisposed()) {
  104982. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  104983. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  104984. this._ground.parent = this._rootMesh;
  104985. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  104986. }
  104987. this._ground.receiveShadows = this._options.enableGroundShadow;
  104988. };
  104989. /**
  104990. * Setup the ground material according to the specified options.
  104991. */
  104992. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  104993. if (!this._groundMaterial) {
  104994. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  104995. }
  104996. this._groundMaterial.alpha = this._options.groundOpacity;
  104997. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  104998. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  104999. this._groundMaterial.primaryColor = this._options.groundColor;
  105000. this._groundMaterial.useRGBColor = false;
  105001. this._groundMaterial.enableNoise = true;
  105002. if (this._ground) {
  105003. this._ground.material = this._groundMaterial;
  105004. }
  105005. };
  105006. /**
  105007. * Setup the ground diffuse texture according to the specified options.
  105008. */
  105009. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  105010. if (!this._groundMaterial) {
  105011. return;
  105012. }
  105013. if (this._groundTexture) {
  105014. return;
  105015. }
  105016. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  105017. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  105018. return;
  105019. }
  105020. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  105021. diffuseTexture.gammaSpace = false;
  105022. diffuseTexture.hasAlpha = true;
  105023. this._groundMaterial.diffuseTexture = diffuseTexture;
  105024. };
  105025. /**
  105026. * Setup the ground mirror texture according to the specified options.
  105027. */
  105028. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  105029. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105030. if (!this._groundMirror) {
  105031. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  105032. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  105033. this._groundMirror.anisotropicFilteringLevel = 1;
  105034. this._groundMirror.wrapU = wrapping;
  105035. this._groundMirror.wrapV = wrapping;
  105036. this._groundMirror.gammaSpace = false;
  105037. if (this._groundMirror.renderList) {
  105038. for (var i = 0; i < this._scene.meshes.length; i++) {
  105039. var mesh = this._scene.meshes[i];
  105040. if (mesh !== this._ground &&
  105041. mesh !== this._skybox &&
  105042. mesh !== this._rootMesh) {
  105043. this._groundMirror.renderList.push(mesh);
  105044. }
  105045. }
  105046. }
  105047. }
  105048. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  105049. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  105050. };
  105051. /**
  105052. * Setup the ground to receive the mirror texture.
  105053. */
  105054. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  105055. if (this._groundMaterial) {
  105056. this._groundMaterial.reflectionTexture = this._groundMirror;
  105057. this._groundMaterial.reflectionFresnel = true;
  105058. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  105059. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  105060. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  105061. }
  105062. };
  105063. /**
  105064. * Setup the skybox according to the specified options.
  105065. */
  105066. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  105067. var _this = this;
  105068. if (!this._skybox || this._skybox.isDisposed()) {
  105069. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  105070. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  105071. }
  105072. this._skybox.parent = this._rootMesh;
  105073. };
  105074. /**
  105075. * Setup the skybox material according to the specified options.
  105076. */
  105077. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  105078. if (!this._skybox) {
  105079. return;
  105080. }
  105081. if (!this._skyboxMaterial) {
  105082. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  105083. }
  105084. this._skyboxMaterial.useRGBColor = false;
  105085. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  105086. this._skyboxMaterial.enableNoise = true;
  105087. this._skybox.material = this._skyboxMaterial;
  105088. };
  105089. /**
  105090. * Setup the skybox reflection texture according to the specified options.
  105091. */
  105092. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  105093. if (!this._skyboxMaterial) {
  105094. return;
  105095. }
  105096. if (this._skyboxTexture) {
  105097. return;
  105098. }
  105099. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  105100. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  105101. return;
  105102. }
  105103. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  105104. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  105105. this._skyboxTexture.gammaSpace = false;
  105106. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  105107. };
  105108. /**
  105109. * Dispose all the elements created by the Helper.
  105110. */
  105111. EnvironmentHelper.prototype.dispose = function () {
  105112. if (this._groundMaterial) {
  105113. this._groundMaterial.dispose(true, true);
  105114. }
  105115. if (this._skyboxMaterial) {
  105116. this._skyboxMaterial.dispose(true, true);
  105117. }
  105118. this._rootMesh.dispose(false);
  105119. };
  105120. /**
  105121. * Default ground texture URL.
  105122. */
  105123. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  105124. /**
  105125. * Default skybox texture URL.
  105126. */
  105127. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  105128. /**
  105129. * Default environment texture URL.
  105130. */
  105131. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  105132. return EnvironmentHelper;
  105133. }());
  105134. BABYLON.EnvironmentHelper = EnvironmentHelper;
  105135. })(BABYLON || (BABYLON = {}));
  105136. //# sourceMappingURL=babylon.environmentHelper.js.map
  105137. var BABYLON;
  105138. (function (BABYLON) {
  105139. /** Internal class used to store shapes for emitters */
  105140. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  105141. function ParticleSystemSetEmitterCreationOptions() {
  105142. }
  105143. return ParticleSystemSetEmitterCreationOptions;
  105144. }());
  105145. /**
  105146. * Represents a set of particle systems working together to create a specific effect
  105147. */
  105148. var ParticleSystemSet = /** @class */ (function () {
  105149. function ParticleSystemSet() {
  105150. /**
  105151. * Gets the particle system list
  105152. */
  105153. this.systems = new Array();
  105154. }
  105155. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  105156. /**
  105157. * Gets the emitter node used with this set
  105158. */
  105159. get: function () {
  105160. return this._emitterNode;
  105161. },
  105162. enumerable: true,
  105163. configurable: true
  105164. });
  105165. /**
  105166. * Creates a new emitter mesh as a sphere
  105167. * @param options defines the options used to create the sphere
  105168. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  105169. * @param scene defines the hosting scene
  105170. */
  105171. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  105172. if (this._emitterNode) {
  105173. this._emitterNode.dispose();
  105174. }
  105175. this._emitterCreationOptions = {
  105176. kind: "Sphere",
  105177. options: options,
  105178. renderingGroupId: renderingGroupId
  105179. };
  105180. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  105181. emitterMesh.renderingGroupId = renderingGroupId;
  105182. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  105183. material.emissiveColor = options.color;
  105184. emitterMesh.material = material;
  105185. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  105186. var system = _a[_i];
  105187. system.emitter = emitterMesh;
  105188. }
  105189. this._emitterNode = emitterMesh;
  105190. };
  105191. /**
  105192. * Starts all particle systems of the set
  105193. * @param emitter defines an optional mesh to use as emitter for the particle systems
  105194. */
  105195. ParticleSystemSet.prototype.start = function (emitter) {
  105196. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  105197. var system = _a[_i];
  105198. if (emitter) {
  105199. system.emitter = emitter;
  105200. }
  105201. system.start();
  105202. }
  105203. };
  105204. /**
  105205. * Release all associated resources
  105206. */
  105207. ParticleSystemSet.prototype.dispose = function () {
  105208. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  105209. var system = _a[_i];
  105210. system.dispose();
  105211. }
  105212. this.systems = [];
  105213. if (this._emitterNode) {
  105214. this._emitterNode.dispose();
  105215. this._emitterNode = null;
  105216. }
  105217. };
  105218. /**
  105219. * Serialize the set into a JSON compatible object
  105220. * @returns a JSON compatible representation of the set
  105221. */
  105222. ParticleSystemSet.prototype.serialize = function () {
  105223. var result = {};
  105224. result.systems = [];
  105225. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  105226. var system = _a[_i];
  105227. result.systems.push(system.serialize());
  105228. }
  105229. if (this._emitterNode) {
  105230. result.emitter = this._emitterCreationOptions;
  105231. }
  105232. return result;
  105233. };
  105234. /**
  105235. * Parse a new ParticleSystemSet from a serialized source
  105236. * @param data defines a JSON compatible representation of the set
  105237. * @param scene defines the hosting scene
  105238. * @param gpu defines if we want GPU particles or CPU particles
  105239. * @returns a new ParticleSystemSet
  105240. */
  105241. ParticleSystemSet.Parse = function (data, scene, gpu) {
  105242. if (gpu === void 0) { gpu = false; }
  105243. var result = new ParticleSystemSet();
  105244. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  105245. scene = scene || BABYLON.Engine.LastCreatedScene;
  105246. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  105247. var system = _a[_i];
  105248. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  105249. }
  105250. if (data.emitter) {
  105251. var options = data.emitter.options;
  105252. switch (data.emitter.kind) {
  105253. case "Sphere":
  105254. result.setEmitterAsSphere({
  105255. diameter: options.diameter,
  105256. segments: options.segments,
  105257. color: BABYLON.Color3.FromArray(options.color)
  105258. }, data.emitter.renderingGroupId, scene);
  105259. break;
  105260. }
  105261. }
  105262. return result;
  105263. };
  105264. return ParticleSystemSet;
  105265. }());
  105266. BABYLON.ParticleSystemSet = ParticleSystemSet;
  105267. })(BABYLON || (BABYLON = {}));
  105268. //# sourceMappingURL=babylon.particleSystemSet.js.map
  105269. var BABYLON;
  105270. (function (BABYLON) {
  105271. /**
  105272. * This class is made for on one-liner static method to help creating particle system set.
  105273. */
  105274. var ParticleHelper = /** @class */ (function () {
  105275. function ParticleHelper() {
  105276. }
  105277. /**
  105278. * Create a default particle system that you can tweak
  105279. * @param emitter defines the emitter to use
  105280. * @param capacity defines the system capacity (default is 500 particles)
  105281. * @param scene defines the hosting scene
  105282. * @returns the new Particle system
  105283. */
  105284. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  105285. if (capacity === void 0) { capacity = 500; }
  105286. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  105287. system.emitter = emitter;
  105288. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  105289. system.createConeEmitter(0.1, Math.PI / 4);
  105290. // Particle color
  105291. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  105292. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  105293. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  105294. // Particle Size
  105295. system.minSize = 0.1;
  105296. system.maxSize = 0.1;
  105297. // Emission speed
  105298. system.minEmitPower = 2;
  105299. system.maxEmitPower = 2;
  105300. // Update speed
  105301. system.updateSpeed = 1 / 60;
  105302. system.emitRate = 30;
  105303. return system;
  105304. };
  105305. /**
  105306. * This is the main static method (one-liner) of this helper to create different particle systems
  105307. * @param type This string represents the type to the particle system to create
  105308. * @param scene The scene where the particle system should live
  105309. * @param gpu If the system will use gpu
  105310. * @returns the ParticleSystemSet created
  105311. */
  105312. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  105313. if (gpu === void 0) { gpu = false; }
  105314. if (!scene) {
  105315. scene = BABYLON.Engine.LastCreatedScene;
  105316. ;
  105317. }
  105318. var token = {};
  105319. scene._addPendingData(token);
  105320. return new Promise(function (resolve, reject) {
  105321. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  105322. scene._removePendingData(token);
  105323. return reject("Particle system with GPU is not supported.");
  105324. }
  105325. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  105326. scene._removePendingData(token);
  105327. var newData = JSON.parse(data.toString());
  105328. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  105329. }, undefined, undefined, undefined, function (req, exception) {
  105330. scene._removePendingData(token);
  105331. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  105332. });
  105333. });
  105334. };
  105335. /**
  105336. * Static function used to export a particle system to a ParticleSystemSet variable.
  105337. * Please note that the emitter shape is not exported
  105338. * @param system defines the particle systems to export
  105339. */
  105340. ParticleHelper.ExportSet = function (systems) {
  105341. var set = new BABYLON.ParticleSystemSet();
  105342. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  105343. var system = systems_1[_i];
  105344. set.systems.push(system);
  105345. }
  105346. return set;
  105347. };
  105348. /**
  105349. * Gets or sets base Assets URL
  105350. */
  105351. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  105352. return ParticleHelper;
  105353. }());
  105354. BABYLON.ParticleHelper = ParticleHelper;
  105355. })(BABYLON || (BABYLON = {}));
  105356. //# sourceMappingURL=babylon.particleHelper.js.map
  105357. var BABYLON;
  105358. (function (BABYLON) {
  105359. /**
  105360. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  105361. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  105362. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  105363. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  105364. */
  105365. var VideoDome = /** @class */ (function (_super) {
  105366. __extends(VideoDome, _super);
  105367. /**
  105368. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  105369. * @param name Element's name, child elements will append suffixes for their own names.
  105370. * @param urlsOrVideo defines the url(s) or the video element to use
  105371. * @param options An object containing optional or exposed sub element properties
  105372. */
  105373. function VideoDome(name, urlsOrVideo, options, scene) {
  105374. var _this = _super.call(this, name, scene) || this;
  105375. _this._useDirectMapping = false;
  105376. // set defaults and manage values
  105377. name = name || "videoDome";
  105378. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  105379. options.clickToPlay = Boolean(options.clickToPlay);
  105380. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  105381. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  105382. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  105383. if (options.useDirectMapping === undefined) {
  105384. _this._useDirectMapping = true;
  105385. }
  105386. else {
  105387. _this._useDirectMapping = options.useDirectMapping;
  105388. }
  105389. _this._setReady(false);
  105390. // create
  105391. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  105392. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  105393. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  105394. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  105395. texture.onLoadObservable.addOnce(function () {
  105396. _this._setReady(true);
  105397. });
  105398. // configure material
  105399. material.useEquirectangularFOV = true;
  105400. material.fovMultiplier = 1.0;
  105401. material.opacityFresnel = false;
  105402. if (_this._useDirectMapping) {
  105403. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105404. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105405. material.diffuseTexture = texture;
  105406. }
  105407. else {
  105408. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  105409. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105410. material.reflectionTexture = texture;
  105411. }
  105412. // configure mesh
  105413. _this._mesh.material = material;
  105414. _this._mesh.parent = _this;
  105415. // optional configuration
  105416. if (options.clickToPlay) {
  105417. scene.onPointerUp = function () {
  105418. _this._videoTexture.video.play();
  105419. };
  105420. }
  105421. return _this;
  105422. }
  105423. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  105424. /**
  105425. * Gets the video texture being displayed on the sphere
  105426. */
  105427. get: function () {
  105428. return this._videoTexture;
  105429. },
  105430. enumerable: true,
  105431. configurable: true
  105432. });
  105433. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  105434. /**
  105435. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  105436. * Also see the options.resolution property.
  105437. */
  105438. get: function () {
  105439. return this._material.fovMultiplier;
  105440. },
  105441. set: function (value) {
  105442. this._material.fovMultiplier = value;
  105443. },
  105444. enumerable: true,
  105445. configurable: true
  105446. });
  105447. /**
  105448. * Releases resources associated with this node.
  105449. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  105450. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  105451. */
  105452. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  105453. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  105454. this._videoTexture.dispose();
  105455. this._mesh.dispose();
  105456. this._material.dispose();
  105457. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  105458. };
  105459. return VideoDome;
  105460. }(BABYLON.TransformNode));
  105461. BABYLON.VideoDome = VideoDome;
  105462. })(BABYLON || (BABYLON = {}));
  105463. //# sourceMappingURL=babylon.videoDome.js.map
  105464. var BABYLON;
  105465. (function (BABYLON) {
  105466. /**
  105467. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  105468. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  105469. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  105470. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  105471. */
  105472. var PhotoDome = /** @class */ (function (_super) {
  105473. __extends(PhotoDome, _super);
  105474. /**
  105475. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  105476. * @param name Element's name, child elements will append suffixes for their own names.
  105477. * @param urlsOfPhoto define the url of the photo to display
  105478. * @param options An object containing optional or exposed sub element properties
  105479. */
  105480. function PhotoDome(name, urlOfPhoto, options, scene) {
  105481. var _this = _super.call(this, name, scene) || this;
  105482. _this._useDirectMapping = false;
  105483. // set defaults and manage values
  105484. name = name || "photoDome";
  105485. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  105486. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  105487. if (options.useDirectMapping === undefined) {
  105488. _this._useDirectMapping = true;
  105489. }
  105490. else {
  105491. _this._useDirectMapping = options.useDirectMapping;
  105492. }
  105493. _this._setReady(false);
  105494. // create
  105495. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  105496. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  105497. // configure material
  105498. material.opacityFresnel = false;
  105499. material.useEquirectangularFOV = true;
  105500. material.fovMultiplier = 1.0;
  105501. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  105502. _this.photoTexture.onLoadObservable.addOnce(function () {
  105503. _this._setReady(true);
  105504. });
  105505. // configure mesh
  105506. _this._mesh.material = material;
  105507. _this._mesh.parent = _this;
  105508. return _this;
  105509. }
  105510. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  105511. /**
  105512. * Gets or sets the texture being displayed on the sphere
  105513. */
  105514. get: function () {
  105515. return this._photoTexture;
  105516. },
  105517. set: function (value) {
  105518. if (this._photoTexture === value) {
  105519. return;
  105520. }
  105521. this._photoTexture = value;
  105522. if (this._useDirectMapping) {
  105523. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105524. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105525. this._material.diffuseTexture = this._photoTexture;
  105526. }
  105527. else {
  105528. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  105529. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105530. this._material.reflectionTexture = this._photoTexture;
  105531. }
  105532. },
  105533. enumerable: true,
  105534. configurable: true
  105535. });
  105536. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  105537. /**
  105538. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  105539. * Also see the options.resolution property.
  105540. */
  105541. get: function () {
  105542. return this._material.fovMultiplier;
  105543. },
  105544. set: function (value) {
  105545. this._material.fovMultiplier = value;
  105546. },
  105547. enumerable: true,
  105548. configurable: true
  105549. });
  105550. /**
  105551. * Releases resources associated with this node.
  105552. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  105553. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  105554. */
  105555. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  105556. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  105557. this._photoTexture.dispose();
  105558. this._mesh.dispose();
  105559. this._material.dispose();
  105560. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  105561. };
  105562. return PhotoDome;
  105563. }(BABYLON.TransformNode));
  105564. BABYLON.PhotoDome = PhotoDome;
  105565. })(BABYLON || (BABYLON = {}));
  105566. //# sourceMappingURL=babylon.photoDome.js.map
  105567. var BABYLON;
  105568. (function (BABYLON) {
  105569. BABYLON.Engine.prototype.createQuery = function () {
  105570. return this._gl.createQuery();
  105571. };
  105572. BABYLON.Engine.prototype.deleteQuery = function (query) {
  105573. this._gl.deleteQuery(query);
  105574. return this;
  105575. };
  105576. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  105577. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  105578. };
  105579. BABYLON.Engine.prototype.getQueryResult = function (query) {
  105580. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  105581. };
  105582. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  105583. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  105584. this._gl.beginQuery(glAlgorithm, query);
  105585. return this;
  105586. };
  105587. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  105588. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  105589. this._gl.endQuery(glAlgorithm);
  105590. return this;
  105591. };
  105592. BABYLON.Engine.prototype._createTimeQuery = function () {
  105593. var timerQuery = this.getCaps().timerQuery;
  105594. if (timerQuery.createQueryEXT) {
  105595. return timerQuery.createQueryEXT();
  105596. }
  105597. return this.createQuery();
  105598. };
  105599. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  105600. var timerQuery = this.getCaps().timerQuery;
  105601. if (timerQuery.deleteQueryEXT) {
  105602. timerQuery.deleteQueryEXT(query);
  105603. return;
  105604. }
  105605. this.deleteQuery(query);
  105606. };
  105607. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  105608. var timerQuery = this.getCaps().timerQuery;
  105609. if (timerQuery.getQueryObjectEXT) {
  105610. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  105611. }
  105612. return this.getQueryResult(query);
  105613. };
  105614. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  105615. var timerQuery = this.getCaps().timerQuery;
  105616. if (timerQuery.getQueryObjectEXT) {
  105617. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  105618. }
  105619. return this.isQueryResultAvailable(query);
  105620. };
  105621. BABYLON.Engine.prototype.startTimeQuery = function () {
  105622. var caps = this.getCaps();
  105623. var timerQuery = caps.timerQuery;
  105624. if (!timerQuery) {
  105625. return null;
  105626. }
  105627. var token = new BABYLON._TimeToken();
  105628. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  105629. if (caps.canUseTimestampForTimerQuery) {
  105630. token._startTimeQuery = this._createTimeQuery();
  105631. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  105632. }
  105633. else {
  105634. if (this._currentNonTimestampToken) {
  105635. return this._currentNonTimestampToken;
  105636. }
  105637. token._timeElapsedQuery = this._createTimeQuery();
  105638. if (timerQuery.beginQueryEXT) {
  105639. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  105640. }
  105641. else {
  105642. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  105643. }
  105644. this._currentNonTimestampToken = token;
  105645. }
  105646. return token;
  105647. };
  105648. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  105649. var caps = this.getCaps();
  105650. var timerQuery = caps.timerQuery;
  105651. if (!timerQuery || !token) {
  105652. return -1;
  105653. }
  105654. if (caps.canUseTimestampForTimerQuery) {
  105655. if (!token._startTimeQuery) {
  105656. return -1;
  105657. }
  105658. if (!token._endTimeQuery) {
  105659. token._endTimeQuery = this._createTimeQuery();
  105660. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  105661. }
  105662. }
  105663. else if (!token._timeElapsedQueryEnded) {
  105664. if (!token._timeElapsedQuery) {
  105665. return -1;
  105666. }
  105667. if (timerQuery.endQueryEXT) {
  105668. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  105669. }
  105670. else {
  105671. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  105672. }
  105673. token._timeElapsedQueryEnded = true;
  105674. }
  105675. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  105676. var available = false;
  105677. if (token._endTimeQuery) {
  105678. available = this._getTimeQueryAvailability(token._endTimeQuery);
  105679. }
  105680. else if (token._timeElapsedQuery) {
  105681. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  105682. }
  105683. if (available && !disjoint) {
  105684. var result = 0;
  105685. if (caps.canUseTimestampForTimerQuery) {
  105686. if (!token._startTimeQuery || !token._endTimeQuery) {
  105687. return -1;
  105688. }
  105689. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  105690. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  105691. result = timeEnd - timeStart;
  105692. this._deleteTimeQuery(token._startTimeQuery);
  105693. this._deleteTimeQuery(token._endTimeQuery);
  105694. token._startTimeQuery = null;
  105695. token._endTimeQuery = null;
  105696. }
  105697. else {
  105698. if (!token._timeElapsedQuery) {
  105699. return -1;
  105700. }
  105701. result = this._getTimeQueryResult(token._timeElapsedQuery);
  105702. this._deleteTimeQuery(token._timeElapsedQuery);
  105703. token._timeElapsedQuery = null;
  105704. token._timeElapsedQueryEnded = false;
  105705. this._currentNonTimestampToken = null;
  105706. }
  105707. return result;
  105708. }
  105709. return -1;
  105710. };
  105711. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  105712. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  105713. };
  105714. // We also need to update AbstractMesh as there is a portion of the code there
  105715. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  105716. var engine = this.getEngine();
  105717. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  105718. this._isOccluded = false;
  105719. return;
  105720. }
  105721. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  105722. this._isOccluded = false;
  105723. return;
  105724. }
  105725. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  105726. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  105727. if (isOcclusionQueryAvailable) {
  105728. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  105729. this._isOcclusionQueryInProgress = false;
  105730. this._occlusionInternalRetryCounter = 0;
  105731. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  105732. }
  105733. else {
  105734. this._occlusionInternalRetryCounter++;
  105735. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  105736. this._isOcclusionQueryInProgress = false;
  105737. this._occlusionInternalRetryCounter = 0;
  105738. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  105739. // if strict continue the last state of the object.
  105740. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  105741. }
  105742. else {
  105743. return;
  105744. }
  105745. }
  105746. }
  105747. var scene = this.getScene();
  105748. if (scene.getBoundingBoxRenderer) {
  105749. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  105750. if (!this._occlusionQuery) {
  105751. this._occlusionQuery = engine.createQuery();
  105752. }
  105753. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  105754. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  105755. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  105756. this._isOcclusionQueryInProgress = true;
  105757. }
  105758. };
  105759. })(BABYLON || (BABYLON = {}));
  105760. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  105761. var BABYLON;
  105762. (function (BABYLON) {
  105763. /**
  105764. * Class used to generate noise procedural textures
  105765. */
  105766. var NoiseProceduralTexture = /** @class */ (function (_super) {
  105767. __extends(NoiseProceduralTexture, _super);
  105768. /**
  105769. * Creates a new NoiseProceduralTexture
  105770. * @param name defines the name fo the texture
  105771. * @param size defines the size of the texture (default is 256)
  105772. * @param scene defines the hosting scene
  105773. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  105774. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  105775. */
  105776. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  105777. if (size === void 0) { size = 256; }
  105778. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  105779. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  105780. _this._time = 0;
  105781. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  105782. _this.brightness = 0.2;
  105783. /** Defines the number of octaves to process */
  105784. _this.octaves = 3;
  105785. /** Defines the level of persistence (0.8 by default) */
  105786. _this.persistence = 0.8;
  105787. /** Gets or sets animation speed factor (default is 1) */
  105788. _this.animationSpeedFactor = 1;
  105789. _this._updateShaderUniforms();
  105790. return _this;
  105791. }
  105792. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  105793. var scene = this.getScene();
  105794. if (!scene) {
  105795. return;
  105796. }
  105797. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  105798. this.setFloat("brightness", this.brightness);
  105799. this.setInt("octaves", this.octaves);
  105800. this.setFloat("persistence", this.persistence);
  105801. this.setFloat("timeScale", this._time);
  105802. };
  105803. /** Generate the current state of the procedural texture */
  105804. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  105805. this._updateShaderUniforms();
  105806. _super.prototype.render.call(this, useCameraPostProcess);
  105807. };
  105808. /**
  105809. * Serializes this noise procedural texture
  105810. * @returns a serialized noise procedural texture object
  105811. */
  105812. NoiseProceduralTexture.prototype.serialize = function () {
  105813. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  105814. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  105815. return serializationObject;
  105816. };
  105817. /**
  105818. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  105819. * @param parsedTexture defines parsed texture data
  105820. * @param scene defines the current scene
  105821. * @param rootUrl defines the root URL containing noise procedural texture information
  105822. * @returns a parsed NoiseProceduralTexture
  105823. */
  105824. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  105825. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  105826. return texture;
  105827. };
  105828. return NoiseProceduralTexture;
  105829. }(BABYLON.ProceduralTexture));
  105830. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  105831. })(BABYLON || (BABYLON = {}));
  105832. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  105833. var __assign = (this && this.__assign) || Object.assign || function(t) {
  105834. for (var s, i = 1, n = arguments.length; i < n; i++) {
  105835. s = arguments[i];
  105836. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  105837. t[p] = s[p];
  105838. }
  105839. return t;
  105840. };
  105841. var BABYLON;
  105842. (function (BABYLON) {
  105843. /**
  105844. * This can helps recording videos from BabylonJS.
  105845. * This is based on the available WebRTC functionalities of the browser.
  105846. *
  105847. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  105848. */
  105849. var VideoRecorder = /** @class */ (function () {
  105850. /**
  105851. * Create a new VideoCapture object which can help converting what you see in Babylon to
  105852. * a video file.
  105853. * @param engine Defines the BabylonJS Engine you wish to record
  105854. * @param options Defines options that can be used to customized the capture
  105855. */
  105856. function VideoRecorder(engine, options) {
  105857. if (options === void 0) { options = null; }
  105858. if (!VideoRecorder.IsSupported(engine)) {
  105859. throw "Your browser does not support recording so far.";
  105860. }
  105861. var canvas = engine.getRenderingCanvas();
  105862. if (!canvas) {
  105863. throw "The babylon engine must have a canvas to be recorded";
  105864. }
  105865. this._canvas = canvas;
  105866. this._canvas.isRecording = false;
  105867. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  105868. var stream = this._canvas.captureStream(this._options.fps);
  105869. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  105870. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  105871. this._mediaRecorder.onerror = this._handleError.bind(this);
  105872. this._mediaRecorder.onstop = this._handleStop.bind(this);
  105873. }
  105874. /**
  105875. * Returns wehther or not the VideoRecorder is available in your browser.
  105876. * @param engine Defines the Babylon Engine to check the support for
  105877. * @returns true if supported otherwise false
  105878. */
  105879. VideoRecorder.IsSupported = function (engine) {
  105880. var canvas = engine.getRenderingCanvas();
  105881. return (!!canvas && typeof canvas.captureStream === "function");
  105882. };
  105883. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  105884. /**
  105885. * True wether a recording is already in progress.
  105886. */
  105887. get: function () {
  105888. return !!this._canvas && this._canvas.isRecording;
  105889. },
  105890. enumerable: true,
  105891. configurable: true
  105892. });
  105893. /**
  105894. * Stops the current recording before the default capture timeout passed in the startRecording
  105895. * functions.
  105896. */
  105897. VideoRecorder.prototype.stopRecording = function () {
  105898. if (!this._canvas || !this._mediaRecorder) {
  105899. return;
  105900. }
  105901. if (!this.isRecording) {
  105902. return;
  105903. }
  105904. this._canvas.isRecording = false;
  105905. this._mediaRecorder.stop();
  105906. };
  105907. /**
  105908. * Starts recording the canvas for a max duration specified in parameters.
  105909. * @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.
  105910. * @param maxDuration Defines the maximum recording time in seconds.
  105911. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  105912. * @return a promise callback at the end of the recording with the video data in Blob.
  105913. */
  105914. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  105915. var _this = this;
  105916. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  105917. if (maxDuration === void 0) { maxDuration = 7; }
  105918. if (!this._canvas || !this._mediaRecorder) {
  105919. throw "Recorder has already been disposed";
  105920. }
  105921. if (this.isRecording) {
  105922. throw "Recording already in progress";
  105923. }
  105924. if (maxDuration > 0) {
  105925. setTimeout(function () {
  105926. _this.stopRecording();
  105927. }, maxDuration * 1000);
  105928. }
  105929. this._fileName = fileName;
  105930. this._recordedChunks = [];
  105931. this._resolve = null;
  105932. this._reject = null;
  105933. this._canvas.isRecording = true;
  105934. this._mediaRecorder.start(this._options.recordChunckSize);
  105935. return new Promise(function (resolve, reject) {
  105936. _this._resolve = resolve;
  105937. _this._reject = reject;
  105938. });
  105939. };
  105940. /**
  105941. * Releases internal resources used during the recording.
  105942. */
  105943. VideoRecorder.prototype.dispose = function () {
  105944. this._canvas = null;
  105945. this._mediaRecorder = null;
  105946. this._recordedChunks = [];
  105947. this._fileName = null;
  105948. this._resolve = null;
  105949. this._reject = null;
  105950. };
  105951. VideoRecorder.prototype._handleDataAvailable = function (event) {
  105952. if (event.data.size > 0) {
  105953. this._recordedChunks.push(event.data);
  105954. }
  105955. };
  105956. VideoRecorder.prototype._handleError = function (event) {
  105957. this.stopRecording();
  105958. if (this._reject) {
  105959. this._reject(event.error);
  105960. }
  105961. else {
  105962. throw new event.error;
  105963. }
  105964. };
  105965. VideoRecorder.prototype._handleStop = function () {
  105966. this.stopRecording();
  105967. var superBuffer = new Blob(this._recordedChunks);
  105968. if (this._resolve) {
  105969. this._resolve(superBuffer);
  105970. }
  105971. window.URL.createObjectURL(superBuffer);
  105972. if (this._fileName) {
  105973. BABYLON.Tools.Download(superBuffer, this._fileName);
  105974. }
  105975. };
  105976. VideoRecorder._defaultOptions = {
  105977. mimeType: "video/webm",
  105978. fps: 25,
  105979. recordChunckSize: 3000
  105980. };
  105981. return VideoRecorder;
  105982. }());
  105983. BABYLON.VideoRecorder = VideoRecorder;
  105984. })(BABYLON || (BABYLON = {}));
  105985. //# sourceMappingURL=babylon.videoRecorder.js.map
  105986. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  105987. globalObject["BABYLON"] = BABYLON;
  105988. //backwards compatibility
  105989. if(typeof earcut !== 'undefined') {
  105990. globalObject["Earcut"] = {
  105991. earcut: earcut
  105992. };
  105993. }
  105994. return BABYLON;
  105995. });